在onreadystatechange函数中访问类变量的Ajax类错误

时间:2014-01-29 23:24:21

标签: javascript php ajax

我目前正在编写JavaScript Ajax类并遇到错误。在函数processRawData()中,我似乎无法使用this.xhr访问类变量xhr。我得到“无法读取未定义的readyState属性。我当前通过在设置对onreadystatechange函数的引用时传入xhr值来修复此问题但是这似乎不需要,因为我应该能够访问xhr值而不这样做。” / p>

function Ajax()
{
    this.xhr = this.createXmlHttpRequest();
}

Ajax.prototype.createXmlHttpRequest = function()
{
    if (window.XMLHttpRequest) {
        try {
            return new XMLHttpRequest();
        } catch (e) {
            throw new Error("Couldn't create XmlHttpRequest : " + e);
        }
    } else {
        try {
            return new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
            throw new Error("Couldn't create XmlHttpRequest : " + e);
        }
    }
}

Ajax.prototype.request = function(type, url, params, dataType, callback)
{
    if (this.xhr.readyState === 0 || this.xhr.readyState === 4) {
        var isGetWithParams = (type === "GET") ? ((params !== null) ? url + params : url) : url
        this.xhr.open(type, isGetWithParams, true);

        this.xhr.onreadystatechange = this.processRawData(dataType, callback);

        var passInParams = (type === "GET") ? null : ((params !== null) ? params : null);
        this.xhr.send(passInParams);
    }
}

Ajax.prototype.processRawData = function(dataType, callback)
{
     return function()
     {
        if (this.xhr.readyState === 4 && this.xhr.status === 200) {
            switch (dataType) {
                case "text":
                    var data = this.xhr.responseText;
                    break;
                case "xml":
                default:
                    var data = this.xhr.responseXML;
            }

            callback(data);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

看起来你的问题可能是因为在processRawData()中你正在返回另一个函数并引用this.xhr.readyState,但是'this'现在引用了返回函数而不是Ajax类。尝试:

Ajax.prototype.processRawData = function(dataType, callback){

var that = this; //'that' references the current Ajax instance

 return function()
 {
    if (that.xhr.readyState === 4 && that.xhr.status === 200) {...