AJAX的無刷新機制使得在注冊系統中對于注冊名稱的檢測能即時顯示。
常見的用戶注冊是用戶輸入用戶名,后臺程序檢測數據庫中用戶名是否重復而做出注冊的成功與失敗之提示(當用戶注冊重名時將返回重新注冊),或者稍微人性化一點就是在用戶名文本框后添加一個檢測按鈕,讓用戶檢測后再做注冊。
以上操作,對于用戶體驗方面來說是比較“差勁”的,一個很好的用戶體驗就是:當用戶輸入完注冊用戶名后,Web系統應能即時檢查并即時顯示,并在檢查和顯示的同時不影響當前頁面的操作。這也就是“異步獲取數據”的要求,而這正是AJAX的強項
比如如下的示例就能展現AJAX的該功能:
當輸入已經存在的用戶名(如cnbruce、cnrose)時頁面將顯示重名不能注冊(false),否則將顯示可以注冊(true),這為用戶的注冊提供了快速的參考,用戶體驗至上。
那么下面就來說說是如何來實現這樣的功能的。
其實通過如上的t1.htm的源代碼,各位就可以看到AJAX的精髓
首先是定義XMLHttp對象
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
function callServer() {
var u_name = document.getElementById("u_name").value;
if ((u_name == null) || (u_name == "")) return;
var url = "cu.asp?name=" + escape(u_name);
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = updatePage;
xmlHttp.send(null);
}
<!--cu.asp的源碼示例-->
<!--#include file="conn.asp"-->
<%
name=request.querystring("name")
Set rs = Server.CreateObject ("ADODB.Recordset")
sql = "Select * from u_ser where u_name='"&name&"'"
rs.Open sql,conn,1,1
if rs.eof and rs.bof then
response.write("true")
else
response.write("false")
end if
rs.close
set rs=nothing
call CloseDatabase
%>
function updatePage() {
if (xmlHttp.readyState < 4) {
test1.innerHTML="loading...";
}
if (xmlHttp.readyState == 4) {
var response = xmlHttp.responseText;
test1.innerHTML=response;
}
}
新聞熱點
疑難解答
圖片精選