Using hitch / deferred with an xhrGet request

↘锁芯ラ 提交于 2019-12-13 03:57:45

问题


I'm attempted to use deferred and hitch in order to provide a callback for my AJAX request. I'm using the following code:

//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)
    })
})

}

However, when I run this code I get an undefined method error on this.resolve(res). I've printed both this (which resolves to the deferred object) and res and both are not undefined. Why am I getting this error and how to achieve what I'm attempting to do?


回答1:


The ajax methods (xhrGet and xhrPost) return deferred objects when executed. With this deferred object you can then register callback and error callback handlers for when the ajax request completes

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

With this code, someCallbackFunction will be called when your ajax request returns successfully, if the ajax request returns with an error, someErrorFunction will be called.

For your particular code piece you code update it like this:

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
  });
}


来源:https://stackoverflow.com/questions/11157432/using-hitch-deferred-with-an-xhrget-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!