等待 jQuery AJAX 响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6250022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Waiting for jQuery AJAX response(s)
提问by Eax
I have a page that, using jQuery .ajax that is called 100 times (async: true), the problem is that, when they they are all being loaded, I need the system to wait for ALL 100 calls to return before continuing. How would I go about this?
我有一个页面,使用 jQuery .ajax 调用 100 次(异步:true),问题是,当它们都被加载时,我需要系统在继续之前等待所有 100 个调用返回。我该怎么办?
Thanks in advance! :)
提前致谢!:)
Update:
更新:
These calls are made in a for() loop (there's 100 of them :))
这些调用是在 for() 循环中进行的(有 100 个 :))
回答by lonesomeday
The nice way to do this is with $.when
. You can use this as follows:
这样做的好方法是使用$.when
. 您可以按如下方式使用它:
$.when(
$.ajax({/*settings*/}),
$.ajax({/*settings*/}),
$.ajax({/*settings*/}),
$.ajax({/*settings*/}),
).then(function() {
// when all AJAX requests are complete
});
Alternatively, if you have all the AJAX calls in an array, you could use apply
:
或者,如果您在一个数组中拥有所有 AJAX 调用,则可以使用apply
:
$.when.apply($, ajaxReqs);
Note that this requires at least jQuery 1.5.
请注意,这至少需要 jQuery 1.5。
To add the AJAX requests to an array, do something like this:
要将 AJAX 请求添加到数组,请执行以下操作:
var ajaxReqs = [];
for (var i = 0; i < 100; i++) {
ajaxReqs.push($.ajax({
/* AJAX settings */
});
}
$.when.apply($, ajaxReqs).then(function() {
// all requests are complete
});
回答by T9b
This kind of issue crops up everywhere in database SQL design - and although its not precisely the same - the issue is exactly the thing that'll get you: network communications.
这种问题在数据库 SQL 设计中随处可见——尽管并不完全相同——但问题正是你要解决的问题:网络通信。
You need to watch out for it because it'll come back to bite you if you don't do it correctly - ie users will get severely annoyed HAVING to wait. I can't emphasize this enough.
你需要小心它,因为如果你做得不正确,它会回来咬你 - 即用户会因为不得不等待而感到非常恼火。我怎么强调都不过分。
Here's the scenario: You want to transfer many small snippets of information from your server upon request. Each request depends on a number of factors operating efficiently. All of which are OUT OF YOUR CONTROL:
场景如下:您希望根据请求从您的服务器传输许多小信息片段。每个请求取决于许多有效运行的因素。所有这些都超出您的控制:
Wide area Network reposnse time (anywhere in the world right?)
Locak area Network reposnse time (anywhere in the building)
WebServer Load
WebServer Response time
Database response time
Backend Script run time
Javascript run time to process the result
The fact that the browsers are generally limited to 6-8 parallel AJAX requests at once (I think - someone correct me on the exact number)
Multiply that by request (erm...in your case x 100)
乘以请求(呃......在你的情况下x 100)
Get the picture?
得到图片?
It might work blissfully well in test on a local machine. You might even be running your own db and webserver on the exact same machine... but try that in the wild and before long you'll hit unreliability as an issue.
它可能在本地机器上测试时运行良好。您甚至可能在完全相同的机器上运行自己的数据库和网络服务器……但是在野外尝试这样做,不久您就会遇到不可靠性的问题。
Listen, the simplist thing to do is wrap up ALL your parameters into ONE JS array and send that in ONE POST request. Then on the server do all your database selects and roll up the responses into ONE JSON/XML reponse.
听着,最简单的做法是将所有参数包装到一个 JS 数组中,并在一个 POST 请求中发送。然后在服务器上执行所有数据库选择并将响应汇总到一个 JSON/XML 响应中。
At that point you are only ever waiting for ONE AJAX response. You can find all your data in the JSON/XML result.
在这一点上,您只需要等待一个 AJAX 响应。您可以在 JSON/XML 结果中找到所有数据。
Given that you are working with 100 requests you would probably be able to actually measure the time saving with a stopwatch!
鉴于您正在处理 100 个请求,您可能能够用秒表实际测量节省的时间!
Take it from me - do as few network requests as possible.
从我这里拿走它 - 尽可能少地执行网络请求。
回答by Pavel Morshenyuk
You can use Deferred object api. As long as $.ajax returns deferred object you can try the following code to use loop:
您可以使用延迟对象 api。只要 $.ajax 返回延迟对象,您就可以尝试使用以下代码来使用循环:
var ajaxes = [];
for (i = 1; i < 100; i++) {
ajaxes[i] = $.ajax({/*data*/});
}
$.when.apply( ajaxes )
.then(function(){
console.log( 'I fire once all ajax requests have completed!' );
})
.fail(function(){
console.log( 'I fire if one or more requests failed.' );
});
P.S. There is a great article regarding using deferred objects by Eric Hynds Using Deferreds in jQuery 1.5
PS在 jQuery 1.5 中使用延迟对象 Eric Hynds 有一篇关于使用延迟对象的很棒的文章
回答by amustill
100 Ajax calls? Seems a very odd requirement and what you're trying to achieve could quite possibly be achieved using another method:
100 个 Ajax 调用?似乎是一个非常奇怪的要求,您想要实现的目标很可能使用另一种方法来实现:
var i = 0; function myCallback() { alert('Completed 100 times'); } function doAjax() { $.ajax({ url: 'blah.php', data: 'hello=world', success: function(response) { i++; }, complete: function() { if(i < 100) { doAjax(); } else { myCallback(); } } }); } doAjax(); // start
回答by Damien
I'm not a JS guy but I would create a global variable, this would be the counter, and define a timed function to check this global var periodically if it reached 100 or not.
我不是 JS 人,但我会创建一个全局变量,这将是计数器,并定义一个定时函数来定期检查此全局变量是否达到 100。
EDIT: setTimeout()
编辑:setTimeout()