问题描述
我跟里面的一些网址的数组,我希望得到他们的HTML并将它推到另一个阵列(或JSON或别的东西)。
I have an array with some URLs inside, and I want to get their HTML and push it into another array (or JSON or something else).
在code看起来像这样;
The code looks like this;
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
};
现在的问题是,这个code不会等待AJAX()请求,并开始发送received_data空。如何要等到所有的Ajax()请求端(除非使用同步请求)?
The problem is that this code will not wait for the ajax() requests and start sending received_data empty. How to wait until all ajax() requests end (except using synchronous requests) ?
推荐答案
您可以使用 $的返回值。AJAX
为无极
,并等待他们都使用满足 jQuery.when
:
You can use the return value of $.ajax
as a Promise
, and wait for all of them to be fulfilled using 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
});
};
到 $的电话。当
看起来有点古怪,因为它希望接收该系列的S 无极等待为离散的参数,而不是一个数组,所以我们使用
功能#适用
做到这一点。如果你打算这样做了很多,你可能会想扩展jQuery的一点:
The call to $.when
looks a bit funky because it's expecting to receive the series of Promise
s to wait for as discrete arguments, rather than an array, so we use Function#apply
to do that. If you're going to do this a lot, you might want to extend jQuery a bit:
(function($) {
$.whenAll = function() {
return $.when.apply($, arguments);
};
})(jQuery);
那么你的使用就变成了:
Then your use becomes:
$.whenAll(gets).then(function() {
// send received_data to some other server
});
附注:我认为有什么东西在字功能
上面您的真实code(例如, F =功能或
F:功能
如果它在对象文本)。否则,它是一个无效的函数声明,因为它没有名字。 (如果你的执行的有东西,这是一个有效的匿名函数EX pression。)
Side note: I assume there's something in front of the word function
above in your real code (e.g., f = function
, or f: function
if it's in an object literal). Otherwise, it's an invalid function declaration as it has no name. (If you do have something, it's a valid anonymous function expression.)
这篇关于如何让jQuery的等待,直到所有的get()中的每一个请求()得到完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!