用jQuery延迟链接ajax请求 [英] Chaining ajax requests with jQuery's deferred

查看:112
本文介绍了用jQuery延迟链接ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个必须多次调用服务器的Web应用程序。到目前为止,我有一个很长的嵌套回调链;但我想在,然后等功能时使用jQuery的。但是,在使用然后后,我似乎无法再次运行。

I have a web app which must call the server multiple times. So far, I had a long nested callback chain; but I would like to use jQuery's when,then etc. functionality. However, I can't seem to get stuff running again after using a 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 请求。 / p>

What am I doing wrong? I guess its some scoping issue, as I can see the second get call being executed. Using two different args variables does not help as the argument passed to the done function is still the first get request.

推荐答案

作为更新:

使用现代jquery(1.8+)你时不需要初步的,因为 get 会返回延期承诺。

With modern jquery (1.8+) you don't need the preliminary when because get returns a Deferred Promise.

此外, pipe 已弃用。请改用然后。只需确保返回新get的结果,该结果将成为随后的然后 / * done * / fail 调用附加的Promise。

Also, pipe is deprecated. Use then instead. Just be sure to return the result of the new get which becomes the Promise attached to by subsequent then/*done*/fail calls.

所以:

$.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); 
});

这篇关于用jQuery延迟链接ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆