我有一个网络应用程序,它必须多次调用服务器。到目前为止,我有一个很长的嵌套回调链;但我想使用 jQuery 的 when
、then
等功能。但是,在使用 then
之后,我似乎无法再次运行。
$
.when ($.get('pages/run-tool.html'))
.then (function (args)
{
// This works fine
alert(args);
$('#content').replaceWith (args);
$('#progress-bar').progressbar ({value: 0});
})
.then ($.get('pages/test.html'))
.done (function(args)
{
// This prints the same as the last call
alert (args);
});
我做错了什么?我猜这是一些范围界定问题,因为我可以看到正在执行的第二个 get
调用。使用两个不同的 args
变量没有帮助,因为传递给 done 函数的参数仍然是第一个 get
请求。
最佳答案
作为更新:
使用现代 jquery (1.8+),您不需要初步的 when,因为 get 返回一个 Deferred Promise。
此外,pipe 已弃用。改用然后。只需确保返回新 get 的结果,它成为后续 then/*done*/fail 调用附加的 Promise。
所以:
$.get('pages/run-tool.html')
.then (function (args) { // this will run if the above .get succeeds
// This works fine
alert(args);
$('#content').replaceWith (args);
$('#progress-bar').progressbar ({value: 0});
})
.then (function() { // this will run after the above then-handler (assuming it ran)
return $.get('pages/test.html'); // the return value creates a new Deferred object
})
.done (function(args) { // this will run after the second .get succeeds (assuming it ran)
alert (args);
});
关于javascript - 使用 jQuery 的延迟链接 ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8049041/