Ajax的封装

var net = new Object();
// AjaxRequest对象的构造函数
net.AjaxRequest = function (method, url, params, onload) {
    this.xmlhttp = null;
    this.onload = onload;
    this.loadData(method, url, params);
}
net.AjaxRequest.prototype.loadData = function (method, url, params) {
    if (!method) {
        method = "GET";
    }
    if (window.XMLHttpRequest) {
        this.xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (this.xmlhttp) {
        try {
            var loader = this;
            this.xmlhttp.open(method, url, true);
            if (method == "POST") {
                this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            }
            this.xmlhttp.onreadystatechange = function () {
                net.AjaxRequest.onStateChange.call(loader);
            }
            this.xmlhttp.send(params);
        } catch (e) {
            this.onerror.call(this);
        }
    }
}

// 重构回调函数
net.AjaxRequest.onStateChange = function () {
    if (this.xmlhttp.readyState == 4) {
        if (this.xmlhttp.status == 200) {
            this.onload.call(this);
        } else {
            this.onerror.call(this);
        }
    } else {
        this.onload.call(this);
    }
}


 

你可能感兴趣的:(Ajax,function,object,null,url,XMLhttpREquest)