用jQuery延迟链接ajax请求

Ant*_*eru 12 javascript jquery jquery-deferred

我有一个Web应用程序,必须多次调用服务器.到目前为止,我有一个很长的嵌套回调链; 但我想用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);
});
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?我猜它有一些范围问题,因为我可以看到get正在执行的第二个调用.使用两个不同的args变量没有帮助,因为传递给done函数的参数仍然是第一个get请求.

cdr*_*cdr 29

作为更新:

使用现代jquery(1.8+),你不需要初步的,因为get返回Deferred 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); 
});
Run Code Online (Sandbox Code Playgroud)


lon*_*day 12

所有三个回调(两个带有then和带有一个done)都应用于同一个请求 - 原始when呼叫.这是因为then返回相同的Deferred对象而不是新对象,以便您可以添加多个事件处理程序.

你需要pipe改用.

$
.when ($.get('pages/run-tool.html'))
.then (function (args)
{
    // This works fine
    alert(args);
    $('#content').replaceWith (args);
    $('#progress-bar').progressbar ({value: 0});
})
.pipe (function() { 
    return $.get('pages/test.html'); // the return value creates a new Deferred object
})
.done (function(args)
{
    alert (args);
});
Run Code Online (Sandbox Code Playgroud)