使用hitch / deferred与xhrGet请求 [英] Using hitch / deferred with an xhrGet request
问题描述
我试图使用 deferred
和 hitch
,以便为我的AJAX请求提供回调。我使用以下代码:
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)
})
})
}
但是,当我运行这个代码时,我得到一个未定义的方法
this.resolve(res)
中的错误。我已经打印了这个
(它解析为延迟对象)和 res
,两者都不是未定义的。为什么我得到这个错误,以及如何实现我正在试图做的?
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?
推荐答案
ajax方法(xhrGet和xhrPost )执行时返回延迟对象。使用这个延迟对象,您可以在ajax请求完成时注册回调和错误回调处理程序。
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));
使用此代码, someCallbackFunction
将被调用当您的ajax请求成功返回时,如果ajax请求返回错误,将调用 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
});
}
这篇关于使用hitch / deferred与xhrGet请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!