面向对象的JavaScript - AJAX类

时间:2011-11-28 16:51:06

标签: javascript ajax oop scope onreadystatechange

使用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的问题。函数确实被调用,但它似乎停留在readyState为0。

非常感谢任何帮助或见解。如果需要包含更多细节,或者我不清楚某些事情,请告诉我。

1 个答案:

答案 0 :(得分: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);
        } 
    };
}

现在,当你执行this.xmlHttp.onreadystatechange = this.handleRequestStateChange();时,它将返回一个绑定函数,该函数捕获了对this的正确self引用,该引用在实际的onreadystatechange函数中使用

相关问题