0

处理 AJAX 类。这是代码:

function AjaxRequest(params) {
    if (params) {
        this.params = params;
        this.type = "POST";
        this.url = "login.ajax.php";
        this.contentType = "application/x-www-form-urlencoded";
        this.contentLength = params.length;
    }
}

AjaxRequest.prototype.createXmlHttpObject = function() {
    try {
        this.xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
        try {
            this.xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
        }
        catch (e) {}
    }

    if (!this.xmlHttp) {
        alert("Error creating XMLHttpRequestObject");
    }
}

AjaxRequest.prototype.process = function() {
    try {
        if (this.xmlHttp) {
            this.xmlHttp.onreadystatechange = this.handleRequestStateChange();
            this.xmlHttp.open(this.type, this.url, true);
            this.xmlHttp.setRequestHeader("Content-Type", this.contentType);
            this.xmlHttp.setRequestHeader("Content-Length", this.contentLength);
            this.xmlHttp.send(this.params);
            }
        }
        catch (e) {
            document.getElementById("loading").innerHTML = "";
            alert("Unable to connect to server");
        }
    }

AjaxRequest.prototype.handleRequestStateChange = function() {
    try {
        if (this.xmlHttp.readyState == 4 && this.xmlHttp.status == 200) {
            this.handleServerResponse();
        }
    }
    catch (e) {
        alert(this.xmlHttp.statusText);
    }
}

AjaxRequest.prototype.handleServerResponse = function() {
    try {
        document.getElementById("loading").innerHTML = this.xmlHttp.responseText;
    }
    catch (e) {
        alert("Error reading server response");
    }
}

然后显然是这样实例化的:

var ajaxRequest = new AjaxRequest(params);
ajaxRequest.createXmlHttpObject();
ajaxRequest.process();

我的handleRequestStateChange方法有问题,因为它处理xmlHttp.onreadystatechange. 通常,当您为 onreadystatechange 定义函数时,例如在调用它时不包含括号xmlHttp.onreadystatechange = handleRequestStateChange;但是因为我试图保持handleRequestStateChange()在类的范围内,所以我遇到了 onreadystatechange 的问题。该函数确实被调用了,但它似乎卡在了 0 的 readyState 上。

任何帮助或见解将不胜感激。请让我知道是否需要包含更多详细信息,或者我是否不清楚某些事情。

4

1 回答 1

3
AjaxRequest.prototype.handleRequestStateChange = function() {
    var self = this;

    return function() {
        try {
            if (self.xmlHttp.readyState == 4 && self.xmlHttp.status == 200) {
                self.handleServerResponse();
            }
        }
        catch (e) {
            alert(self.xmlHttp.statusText);
        } 
    };
}

Now, when you do this.xmlHttp.onreadystatechange = this.handleRequestStateChange();, it will return a bound function that has trapped the correct this reference to self, which is used inside the actual onreadystatechange function.

于 2011-11-28T16:56:26.380 回答