Ajax In Action 中定义XMLHTTPReqeust对象的代码。
//
初始化XMLHTTPRequest对象
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);
}
}
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!");
}
}