封装好的对象:
var Ajax = function (sUrl, sMethod, oParam, fCallback) {
this.sUrl = sUrl;
this.sMethod = sMethod;
this.oParam = oParam;
this.fCallback = fCallback;
this.status = {
1: '请求成功',
2: 'http返回失败',
3: '数据加载中'
}
this.xmlHttp = null;
//驱动函数
this.Driver = function () {
this.xmlHttp = this.CreateXmlHttp();
this.xmlHttp.open(this.sMethod, this.sUrl, true);
this.xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
this.xmlHttp.onreadystatechange = GetResult; //指定回调函数
this.xmlHttp.send(this.oParam); //发送请求
};
//创建操作对象
this.CreateXmlHttp = function () {
var xmlHttp;
if (window.ActiveXObject) { //IE下
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (window.XMLHttpRequest) { //其他浏览器如火狐
xmlHttp = new XMLHttpRequest();
}
return xmlHttp;
};
//回调方法
var GetResult = function () {
if (this.readyState == 4) {//请求状态为4表示成功
if (this.status == 200) {//http状态200表示OK
eval(fCallback)(this.responseText);
} else {//http返回状态失败
return this.status[2];
}
} else {//请求状态还没有成功,页面等待
return this.status[3];
}
}
}
调用方法:
new Ajax('test.php', 'get', {}, function (responseText) {
alert(responseText);
}).Driver();