如何让jQuery等到每个()中的所有get()请求都完成
我有一个包含一些URL的数组,我想获取他们的HTML并将其推送到另一个数组(或JSON或其他)。
代码看起来像这样;
url = ["/page_1.html", "/page_2.html"]; received_data = []; function() { url.each(function(i) { $.ajax({ type: 'GET', url: this, success: function(data) { received_data.push(data); } }); }); // send received_data to some other server };
问题是这段代码不会等待ajax()请求并开始发送receive_data为空。 如何等待所有ajax()请求结束(除了使用同步请求)?
您可以使用$.ajax
的返回值作为Promise
,并等待使用jQuery.when
实现所有这些:。
function() { var gets = []; url.each(function(i) { gets.push($.ajax({ type: 'GET', url: this, success: function(data) { received_data.push(data); } })); }); $.when.apply($, gets).then(function() { // send received_data to some other server }); };
对$.when
的调用看起来有点时髦,因为它期望接收一系列Promise
等待作为离散参数而不是数组,所以我们使用Function#apply
来做到这一点。 如果你要做很多事情,你可能想要扩展jQuery:
(function($) { $.whenAll = function() { return $.when.apply($, arguments); }; })(jQuery);
然后你的使用变成:
$.whenAll(gets).then(function() { // send received_data to some other server });
旁注:我假设在实际代码中上面的单词function
前面有一些东西(例如, f = function
,或f: function
如果它在对象文字中)。 否则,它是一个无效的函数声明,因为它没有名称。 (如果你确实有某些东西,它是一个有效的匿名函数表达式。)