使用挂钩/延迟与 xhrGet 请求

Using hitch / deferred with an xhrGet request

本文关键字:xhrGet 请求 延迟      更新时间:2023-09-26

我试图使用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)
    })
})

}

但是,当我运行此代码时,我在this.resolve(res)上收到undefined method错误。我已经打印了this(解析为延迟对象)和res,两者都不是未定义的。为什么我会收到此错误以及如何实现我尝试执行的操作?

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