您的位置:首页 > 其它

Ajax 简单封装

2008-09-02 20:30 295 查看
/*********************************************************************************************
Ajax类应用示例代码:
new Ajax({
url: 'readMessageList.action',
onComplete: function(data){document.getElementById('message_div').innerHTML += data;}
}).doRequest();
**********************************************************************************************/

Ajax = function(config)
{
this._xmlHttpRequest = null;
this._userConfig = config;
this._config = {
method: 'get', // get||post|| ...
async: true,
returnDataFormat: 'jsCode', // jsCode||string||xml
url: null,
onComplete: function(data){}
};
this._init = function()
{
if (window.XMLHttpRequest) {
this._xmlHttpRequest = window.XMLHttpRequest;
}
else {
this._xmlHttpRequest = new ActiveXObject('Microsoft.XMLHTTP');
}

};

this.doRequest = function()
{
var instance = this;
if (!this._xmlHttpRequest) {
this._init();
}
if (this._userConfig) {
for (var key in this._userConfig) {
this._config[key] = this._userConfig[key];
}
}
this._xmlHttpRequest.open(this._config.method, this._config.url, this._config.async);
this._xmlHttpRequest.onreadystatechange = function()
{
if (instance._xmlHttpRequest.readyState == 4){
if (instance._xmlHttpRequest.status == 200){
var responseText = instance._xmlHttpRequest.responseText;
if (instance._config.returnDataFormat == 'jsCode') {
instance._config.onComplete(eval('(' + responseText + ')'));
}
else if (instance._config.returnDataFormat == 'string') {
instance._config.onComplete(responseText);
}
else if (instance._config.returnDataFormat == 'xml'){
instance._config.onComplete(instance._xmlHttpRequest.responseXml);
}
}
}

};
instance._xmlHttpRequest.send(null);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: