我需要在进行AJAX调用之前和AJAX调用之后(在调用实际的处理程序方法之前)调用一些常用方法。我正在使用dojo.aspect
来实现这一目标。
这是我的代码示例
function makeAjaxCall(){
dojo.xhrGet({
url:"sample_url",
content:{
test:"value"
},
load:function(response){
//Do some logic here
},
error:function(response){
//handle error
}
});
}
以下是dojo.aspect
,我正在使用XHR
来查看define(["dojo/aspect"], function(aspect){
aspect.after(dojo, "xhr", function(deferred){
console.log("AJAX AFTER");
deferred.then(function(response){
//CALLED AFTER 'load' METHOD IS CALLED.
console.log("Testing");
});
});
aspect.before(dojo, "xhr", function(method, args){
console.log("AJAX BEFORE");
});
});
来电。
deferred.then
现在问题是在调用“aspect.after
”函数后调用load
内的{{1}}。是否可以在调用实际的load方法之前调用一个方法?
答案 0 :(得分:2)
简短的回答是肯定的。
首先,有两种方法可以在Dojo中进行ajax调用。
dojo/xhr
- 这就是您所拥有的内容,不推荐使用此功能
dojo/request/xhr
第一个实现将调用第二个实现。所以我建议在dojo/request/xhr
上使用aop。
aspect.around(require.modules['dojo/request/xhr'], 'result', function(originalXhr){
return function(url, options, returnDeferred){
var dfd = new Deferred();
// Logic before making the xhr call
originalXhr(url, options, returnDeferred)
.then(function(response) {
// Logic handling the response but before resolving the deferred.
dfd.resolve(vm);
// Logic after resolving the deferred.
}, function(err){
// error handling?
dfd.reject(msgs);
}, function(update) {
dfd.progress(update);
});
return dfd;
};
});
您可以在以下位置找到完整的实施方案 https://github.com/cswing/evinceframework/blob/master/evf-web-js/src/dojo/evf/serviceRegistry.js(〜第111行)
用法:
require('dojo/xhr/request', function(xhr){
xhr({...}).then(
function(response) {
//handle response
},
function(error) {
//handle error
}
);
});
dojo/xhr
代码会将自己转换为上述用法,因此您发布的代码应该有效。
答案 1 :(得分:0)
如果您切换到新API - dojo/request
答案 2 :(得分:0)
在Dojo 1.10中,有一个全新的API来全局捕获请求状态。
notify("error", function(error){
console.error(error);
//SyntaxError: Unexpected token < in JSON at position 0(…)
});
但在我的情况下,我在html中得到错误,例如。所以在错误中我得到&#34;错误SyntaxError:意外的令牌&lt;在JSON的位置0(...)&#34;
在以前的版本中,可以访问响应对象:
topic.subscribe("/dojo/io/error", function(/*dojo.Deferred*/ dfd, /*Object*/ response){
if (response.status === 401) {
window.location.reload();
}
});
所以我发现可以自定义json处理程序:
require(["dojo/request/handlers"], function(handlers){
handlers.register("json", function(response){
if (response.status === 401) {
window.location.reload();
return;
}
return JSON.parse(response.text || null);
});
});
这样,您就可以在JSON.parse抛出异常之前检测到response.errors。