【发布时间】:2013-04-01 05:45:06
【问题描述】:
我一直试图了解 jQuery Deferred 对象。我的目的是检查每个 ajax 响应(成功/失败)。我想在不干扰其他声明典型 $.ajax().done().fail() 请求的代码的情况下做到这一点。
我已经使用 $.ajaxPrefilter() 在执行之前获取每个 ajax 请求。在 jqXHR 对象上使用 .then() 方法,我设法添加了一个函数,该函数将在原始 $.ajax() 调用上的 .done() 方法之前调用
下面的代码将打印出以下内容:
定义完成
然后定义
然后是第二个 ajax 预过滤器
第二个 ajax 完成
然后是第二个 ajax
ajax 完成
然后是ajax
我不明白为什么先执行预过滤步骤。我本来希望它最后被执行,或者根本不执行。
行为是我想要的,但我不明白为什么。
// this is a typical usage of deferred with two done functions added, the second via .then()
var def = $.Deferred();
def.done(function(){
document.write("def done<br>");
});
def.then(function(){
document.write("def then<br>");
});
def.resolve();
// this is a typical ajax request with a done function added, followed by another using .then()
$.ajax("/echo/json/").done(function(){
document.write("ajax done<br>");
}).then(function(){
document.write("ajax then<br>");
});
// for the third request i intercept and call the .then() method
$.ajaxPrefilter(
function( options, originalOptions, jqXHR ) {
jqXHR.then(function(data, textStatus, jqXHR){
document.write("2nd ajax prefilter then<br>");
});
});
// create a typical ajax request. these will be executed after the prefilter .then()
$.ajax("/echo/json/").done(function(){
document.write("2nd ajax done<br>");
}).then(function(){
document.write("2nd ajax then<br>");
});
提前感谢您的帮助
更新:------------
来自@Bergi 的响应,下面的代码演示了如何在 done() 之前调用 $.ajaxPrefilter()。
$.ajaxPrefilter(
function( options, originalOptions, jqXHR ) {
document.write("prefilter function within $.ajax call<br>");
jqXHR.then(function(data, textStatus, jqXHR){
document.write("2nd ajax prefilter then<br>");
});
});
var functionToRunWhenDoneIsCalled = function() {
document.write("done is called function<br>");
return function(){
document.write("2nd ajax done<br>");
}
}
$.ajax("/echo/json/").done(
(functionToRunWhenDoneIsCalled)()
).then(function(){
document.write("2nd ajax then<br>");
});
这个输出:
$.ajax 调用中的预过滤函数
done 被称为函数
然后是第二个 ajax 预过滤器
第二个 ajax 完成
然后是第二个 ajax
这回答了我关于 .then() 方法如何在 .done() 方法之前附加到延迟的 jqXHR 对象的问题。
【问题讨论】:
-
您使用的是同步 jax 吗?否则你应该避免
document.write。 -
我最初使用 document.write 创建了一个 jsfiddle 来演示代码,但决定将其改为内联
标签: javascript jquery jquery-deferred