javascript - 使用 jQuery 的延迟链接 ajax 请求

标签 javascript jquery jquery-deferred

我有一个网络应用程序,它必须多次调用服务器。到目前为止,我有一个很长的嵌套回调链;但我想使用 jQuery 的 whenthen 等功能。但是,在使用 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/

相关文章:

jquery - jQuery 的 .ajax 方法如何定义 'failed' 请求?

javascript - tinymce 图像插入,第二次工作但不是第一次

javascript - 为什么改变对象的 [[prototype]] 会降低性能?

javascript - 无效的 Hook 调用。钩子(Hook)只能在函数组件体内调用

Javascript/Jquery - 获取可见图像的链接

javascript - 如何使用 JavaScript 创建带有子项目的可点击的 div 列表

javascript - 不使用 'then' 链接 promise

javascript - jQuery 中延迟对象中的 resolved 和 rejected 是什么意思?

javascript - Tensorflow.js tf.Tensor转JS数

javascript - 根据另一个选择器中的值动态填充一个选择器