Ajax In Action 中定義XMLHTTPReqeust對象的代碼。
function initXMLHTTPRequest()
{
var xRequest = null;
if(Window.XMLHTTPRequest)
{
xRequest = new XMLHTTPRequest();
}
else if ( window.ActiveXObject)
{
xRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
retuen xRequest;
}
//調用
function sendRequest(url,params,HttpMethod)
{
if(!HttpMethod)
{
HttpMethod = "GET";
}
req = initXMLHTTPRequest();
if(req)
{
req.open(HttpMethod,url,true);
req.sendRequestHeader("Content-Type","application/x-www-form-urlencoded");
req.send(params);
}
}
HTTP就緒狀態 ,表示請求的狀態和情形 ,它用於表示請示是否開始、是否得到了響應或是請求響應模式是否已經完成。下面是 Ajax中需要了解的五種就緒狀態:
- 0: 表示請求尚未發出(調用open()之前) 。
- 1:表示請求已經建立但尚未發出(調用send()之前)。
- 2:請求已經發出正在處理之中(這裏通常可以從響應得到的內容頭部)。
- 3:請求已經處理,響應中通常有部分數據 可用,但服務器還沒有完成響應。
- 4:相應已經完成,可以訪問服務器響應並使用它。
function _callBackFunction()
{
if(req.readystate == 4)
{
alert("Server is done!");
}
}