0

こちらのhtml5rocksWebサイトでXMLHttpRequest2のガイドをフォローしています。JavaScriptでクラスを作成する方法も学んでいます。すべてが正しいように見えますが、jsfiddleでこのコードをテストすると、ifステートメントから「エラー」が2回返され、応答が未定義を返します。これはクラスの問題だと思いますか?

function Ajax(parameters) {
    this.type = parameters.type;
    this.url = parameters.url;
    this.format = parameters.format;
    this.send = parameters.send;
    this.xhr = new XMLHttpRequest();
}

Ajax.prototype.initialize = function () {
    this.xhr.open(this.type, this.url, true);
    this.xhr.responseType = this.format;
    this.xhr.onload = this.process();
    this.xhr.send(this.send);
};

Ajax.prototype.process = function () {
    var self = this;
    if (self.xhr.readyState === 4 && self.xhr.status === 200) {
        console.log(JSON.parse(self.xhr.response));
    } else {
      console.log("error");
    }
};

var test = new Ajax({type:"GET", url:"http://ip.jsontest.com/", format:"text", send:""});

test.initialize();

console.log(test.process());
4

1 に答える 1

0

ここでコードを変更しました:http://jsfiddle.net/FpskW/

コードには2つの問題があります。

  1. 初期化では、関数自体ではなく、関数this.xhr.onloadの実行の値を取得します。関数が必要であり、委任する代わりに、最後にコードを実行します。proccessthis.xhr.onload()proccess

  2. そうした場合、特定のコンテキストなしで関数をthis.xhr.onload = this.proccess渡すことになります。proccessこのように、XHRオブジェクトが関数を実行すると、関数はXHRオブジェクトのコンテキストを持ちます。this関数が実行されるときの値はproccess、オブジェクトではなくXHRオブジェクトになります。したがって、xhrオブジェクトを実行しようとするif (self.xhr.readyState === 4..と、XHRオブジェクトにxhrというプロパティがないことがわかります。

あなたはこのようなことをすることができます:

    Ajax.prototype.initialize = function () {
      this.xhr.open(this.type, this.url, true);
      this.xhr.responseType = this.format;

      // we capture the context of the Ajax object
      var self = this;

      // and we create a lambda that executes the 'proccess' function always with the context
      // of the Ajax object.
      this.xhr.onload = function() {
        self.process();
      }

      this.xhr.send(this.send);
    };

そしてそれがすべてです。

注:Javascriptにはクラスがなく、プロトタイプです。:)

于 2013-01-08T08:05:13.880 に答える