简单的ajax类...
时间:2010-08-07 来源:jnssvh
/**
* Ajax处理类
Ajax.request({url:"test.jsp?type=ajax", rollback:result});
*/
function Ajax(initObj)
{
this.xmlHttp = Ajax.getXmlHttpObject();
this.initObj = initObj;
this.checkParam();
}
Ajax.request = function (initObj)
{
var ajax = new Ajax(initObj);
ajax.send();
};
Ajax.prototype.checkParam = function(){
var thisObj = this;
//请求方法
if (this.initObj.method == undefined)
{
this.initObj.method = "get";
}
else if (this.initObj.method.toLowerCase() != "post")
{
this.initObj.method = "get";
}
//post请求数据
if (this.initObj.method.toLowerCase() == "post")
{
var len = 0;
if (this.initObj.data == undefined || this.initObj.data == "")
{
this.initObj.data = null;
}
else
{
len = this.initObj.data.length;
}
this.xmlHttp.setrequestheader("content-length", len);
this.xmlHttp.setrequestheader("content-type", "application/x-www-form-urlencoded;charset=utf-8");
}
else
{
this.initObj.data = null;
}
if (this.initObj.url == undefined)
{
this.initObj.url = "";
}
if (this.initObj.isAsync == undefined) //布尔型,指定此请求是否为异步方式,默认为true。如果为真,当状态改变时会调用onreadystatechange属性指定的回调函数。
{
this.initObj.isAsync = true;
}
if (this.initObj.returnType == undefined) //text, xml
{
this.initObj.returnType = "text";
}
thisObj.xmlHttp.onreadystatechange = function()
{
var state = thisObj.xmlHttp.readyState;
switch (state)
{
case 0: //未初始化,对象已建立,但是尚未初始化(尚未调用open方法)
break;
case 1: //初始化,对象已建立,尚未调用send方法
break;
case 2: //发送数据,send方法已调用,但是当前的状态及http头未知
break;
case 3: //数据传送中,已接收部分数据,因为响应及http头不全,这时通过responseBody和responseText获取部分数据会出现错误,
break;
case 4: //完成,数据接收完毕,此时可以通过通过responseBody和responseText获取完整的回应数据
var response;
if (thisObj.initObj.returnType == "text") //text, xml
{
response = thisObj.xmlHttp.responseText; //将响应信息作为字符串返回
}
else
{
try {
response = thisObj.xmlHttp.responseXML; //将响应信息格式化为Xml Document对象并返回
} catch (e) {
response = null;
}
}
switch (thisObj.xmlHttp.status)
{
case 200:
if (typeof thisObj.initObj.rollback == "function")
{
thisObj.initObj.rollback(response, 200);
}
break;
case 304:
if (typeof thisObj.initObj.rollback == "function")
{
thisObj.initObj.rollback(response, 304);
}
break;
case 404:
alert("Ajax请求文件(" + thisObj.initObj.url + ")没发现。" + "\n=== === ===\n" + response);
break;
default:
alert("Ajax返回状态码:" + thisObj.xmlHttp.status + "未处理");
break;
}
thisObj.initObj.rollBack = null;
thisObj.initObj = null;
thisObj.xmlHttp = null;
break;
default:
break;
}
}
};
Ajax.getXmlHttpObject = function() {
var fns = [
function () { return new XMLHttpRequest(); },
function () { return new ActiveXObject('Msxml2.XMLHTTP'); },
function () { return new ActiveXObject('Microsoft.XMLHTTP'); },
];
for (var i = 0,n=fns.length; i < n; i++) {
try {
fns[i]();
Ajax.getXmlHttpObject = fns[i];//注意这里,用于重置函数
break;
}catch(e){}
}
return Ajax.getXmlHttpObject();
};
Ajax.prototype.send = function()
{
this.xmlHttp.open(this.initObj.method, this.initObj.url, this.initObj.isAsync);
this.xmlHttp.setRequestHeader("If-Modified-Since","0");
this.xmlHttp.send(this.initObj.data);
};