0

AJAX リクエストにコールバックを提供するためにdeferredandを使用しようとしています。hitch私は次のコードを使用しています:

//Code is executed from this function
function getContent(){
    var def = new dojo.Deferred();
    def.then(function(res){
    console.lod("DONE");
    console.log(res);
    },
    function(err){
        console.log("There was a problem...");
    });
    this.GET("path", def);
}

//Then GET is called to perform the AJAX request...
function GET(path, def){
dojo.xhrGet({
    url : path,
    load : dojo.hitch(def,function(res){
        this.resolve(res);  
    }),
    error : dojo.hitch(def, function(err){
        this.reject(err)
    })
})

}

ただし、このコードを実行すると、でundefined methodエラーが発生しthis.resolve(res)ます。私はthis(遅延オブジェクトに解決される)両方を印刷しましたresが、両方とも未定義ではありません。このエラーが発生するのはなぜですか? また、何をしようとしているのですか?

4

1 に答える 1

1

ajaxメソッド(xhrGetおよびxhrPost)は、実行時に遅延オブジェクトを返します。この遅延オブジェクトを使用すると、ajaxリクエストが完了したときのコールバックハンドラーとエラーコールバックハンドラーを登録できます。

var deferred = dojo.xhrGet({url:'someUrl'});
deferred.then(dojo.hitch(this,this.someCallbackFunction),dojo.hitch(this,this.someErrorFunction));

このコードでsomeCallbackFunctionは、ajaxリクエストが正常に戻ったときに呼び出され、ajaxリクエストがエラーで戻った場合someErrorFunctionに呼び出されます。

特定のコードピースについては、次のようにコードを更新します。

function getContent(){
    var resultFunction = function(res){
      console.lod("DONE");
      console.log(res);
    };
    var errorFunction = function(err){
      console.log("There was a problem...");
    };
    this.GET("path").then(dojo.hitch(this,resultFunction),dojo.hitch(this,errorFunction);
}

//Then GET is called to perform the AJAX request...
function GET(path){
  return dojo.xhrGet({
    url : path
  });
}
于 2012-06-22T13:56:00.573 に答える