註冊表單最常見的需求之一,是使用者輸入帳號後立刻告訴他這個帳號能不能用。做法是讓 xmlHttp 背景呼叫一支 ASPX 頁面,由該頁面查詢資料庫並回傳結果,前端再依回傳值顯示提示。
<script type="text/javascript" language="javascript">
<!--
// 以 XML 求取資料
function CheckUser(theEmail)
{
var webFileUrl = "../User/CheckUser.aspx?LogonName=" + encodeURIComponent(theEmail);
var result = "";
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
xmlHttp.open("POST", webFileUrl, false);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
result = xmlHttp.responseText;
}
}
xmlHttp.send("");
if (xmlHttp.status != 200)
{
alert('網路故障(xmlHttp.status=' + xmlHttp.status + '),請稍後再試!');
return false;
}
result = xmlHttp.responseText;
result = result.substring(0, result.indexOf("?EX"));
if (result != "false")
{
return true;
}
else
{
return false;
}
}
//-->
</script>
這裡有兩個細節值得注意。第一,查詢字串中的使用者輸入應該用 encodeURIComponent() 編碼,否則遇到 &、= 等字元會讓參數被切錯。第二,範例採同步模式(open 的第三個參數為 false),因此 onreadystatechange 的指定必須寫在 send() 之前才可靠;若改用非同步,判斷順序也要跟著調整。
''' <summary>
''' 檢測使用者是否存在(檔案:../User/CheckUser.aspx)
''' </summary>
Partial Class Web_User_CheckUser
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Request.QueryString("LogonName") Is Nothing Then
Response.Write("false" + "?EX")
Response.End()
Exit Sub
End If
Dim user = New EasyClick.EasyBusiness.UserBusiness() _
.GetUserByLogonName(Request.QueryString("LogonName").ToString())
If user Is Nothing Then
Response.Write("false" + "?EX")
Else
Response.Write("true" + "?EX")
End If
Response.End()
End Sub
End Class
這是一個實用的小技巧。頁面輸出時可能夾帶其他內容(例如空白或額外的標記),前端用 indexOf("?EX") 把這個哨符之前的部分取出來,就能拿到乾淨的 true 或 false,不受其他輸出的干擾。