Ajax 简单封装

来源:互联网 发布:51duino源码 编辑:程序博客网 时间:2024/05/22 13:14

/*********************************************************************************************
 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);
    }
}


 

原创粉丝点击