使用hitch / deferred和xhrGet请求

时间:2012-06-22 13:46:20

标签: javascript ajax dojo

我试图使用deferredhitch来为我的AJAX请求提供回调。我正在使用以下代码:

//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,两者都没有未定义。为什么我会收到此错误以及如何实现我正在尝试做的事情?

1 个答案:

答案 0 :(得分:1)

ajax方法(xhrGet和xhrPost)在执行时返回延迟对象。使用此延迟对象,您可以在ajax请求完成时注册回调和错误回调处理程序

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

使用此代码,当您的ajax请求成功返回时,将调用someCallbackFunction,如果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
  });
}