1

Chrome拡張機能用の単純なajaxクラスを作成しようとしています。コードを実行しようとすると、未定義のエラーが発生 Uncaught TypeError: Cannot read property 'readyState' of undefinedします。この問題の原因は何ですか?

function ajax(arguments, callback) {
    this.xhr = new XMLHttpRequest();
    this.xhr.open(arguments.requestType, arguments.requestUrl + arguments.requestParameters, true);
    this.xhr.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
            requestedData = JSON.parse(this.responseText);
            callback(requestedData);
        }
    }
    this.xhr.send();
}

var ajaxRequest = new ajax({ 
    requestType: 'GET',
    requestUrl: 'http://ezswag.com/bots/terms.php',
    requestParameters: ' ',
    }, function(json) {
        //console.log(json);  => json {apple: "red", cheery: "red"}
        return json;
    });

    console.log(ajaxRequest);

(更新されたコード、および動作中

4

3 に答える 3

4

の値はthis、関数がどのように呼び出されているかによって異なります。

関数をコンストラクターとして呼び出すとajax(慣例では、コンストラクター関数名は大文字で始める必要があることに注意してください)this、作成されるインスタンスです。

readyState関数では、thisはXMLHttpRequestオブジェクトです。

関数this.xhr内へのすべての参照は単純である必要がありますreadyStatethis

于 2013-01-04T14:10:33.853 に答える
1

関数内でthis.xhrを使用することはできません。これは現在の関数への参照を行い、あなたはどう思いますかではありません。

次のような一時変数を使用します。

var self = this;

this.xhr.onreadystatechange = function() {
    if (self.xhr.readyState === 4 && self.xhr.status === 200) {
        requestedData = JSON.parse(self.xhr.responseText);
        console.log(requestedData);
    }
}
于 2013-01-04T14:09:24.443 に答える
1

あなたのonreadystatechange実装でthisは、それはあなたが思っていることではありません。関数のスコープをキャプチャし、ajaxそれをコールバックで使用する必要があります。

function ajax(parameter) {
    var that = this;
    this.xhr = new XMLHttpRequest();
    this.xhr.open(parameter.requestType, parameter.requestUrl + parameter.requestParameters, true);
    this.xhr.onreadystatechange = function() {
        if (that.xhr.readyState === 4 && that.xhr.status === 200) {
            requestedData = JSON.parse(that.xhr.responseText);
            console.log(requestedData);
        }
    }
    this.xhr.send();
}
于 2013-01-04T14:09:41.330 に答える