使用JQuery对多个ajax请求串行执行。
HTML代码:
<a href="#">Click me!</a> <div></div>
JS:
function GetSomeDeferredStuff() { var deferreds = []; var i = 1; for (i = 1; i <= 10; i++) { var count = i; deferreds.push( $.post('/echo/html/', { html: "<p>Task #" + count + " complete.", delay: count }).success(function(data) { $("div").append(data); })); } return deferreds; } $(function() { $("a").click(function() { var deferreds = GetSomeDeferredStuff(); $.when.apply(null, deferreds).done(function() { $("div").append("<p>All done!</p>"); }); }); });
方法类似于Node.js中的q,使用promise defer模式将所有的ajax请求放到一个数组里,然后通过$.when.apply().done()将所有ajax请求依次执行。
这里的apply不是when专用的方法,而是需要将一个数组转化为某个方法的多个参数时可以用到的
The apply()
method calls a function with a given this
value, and arguments
provided as an array (or an array-like object).
Note: While the syntax of this function is almost identical to that of call()
, the fundamental difference is that call()
accepts an argument list, while apply()
accepts a single array of arguments.
var numbers = [5, 6, 2, 3, 7];
var max = Math.max.apply(null, numbers);
console.log(max);
// expected output: 7
var min = Math.min.apply(null, numbers);
console.log(min);
// expected output: 2