首先建立一個XMLHttpRequestXMLHttpRequest
function createRequest()
{
try
{
request = new XMLHttpRequest();
}
catch(trymicrosoft)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(othermicrosoft)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(failed)
{
request = null;
}
}
}
if(request == null)
{
alert("Error,Creating request object!");
}
}
然後開始編寫需要發送非同步請求的方法:
sendAsynchronousRequest
function ajaxLogin()
{
var emailLogin = document.getElementById("UserEmailInput").value;
var passwordLogin = document.getElementById("UserPwdInput").value;
createRequest();
//new Date().getTime() 加上一個隨機時間字元,避免請求緩衝
var url = "AjaxLogin.aspx?Email=" + emailLogin + "&thisTime=" + new Date().getTime();
request.open("GET",url,true);
request.onreadystatechange = updatePageUserLogin; //回呼函數updatePageUserLogin方法名後面被禁止書寫小括弧()
request.send(null);
}
回呼函數執行:
call-back function
function updatePageUserLogin()
{
if(request.readyState == 4)
{
if(request.status == 200)
{
var content = request.responseText;
if(content == "True")
{
//alert("登入成功");
setUserLoginOkCookie(); //使用者登入成功以後給使用者儲存cookie
}
if(content == "False")
{
//alert("失敗");
var html = '<div style="color:"><img src="pic/bg/exit.png"></img> 使用者名稱或密碼錯誤,請重新輸入:</div>';
jQuery("#LoginNameAndPasswordError").html(html);
}
}
}
}
就這樣,優雅簡潔的完成了ajax非同步請求!
不錯吧!努力賺錢給老婆 買個iPhone $4600RMB