Javascript jQuery 等待异步 ajax 调用完成
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10288429/
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
jQuery Wait until async ajax calls are finished
提问by user1352324
Hi I have 2 ajax calls in my script, I need them run asnyc to spare time, but I need the second to wait until the first is finished.
嗨,我的脚本中有 2 个 ajax 调用,我需要它们运行 asnyc 以腾出时间,但我需要第二个等待,直到第一个调用完成。
$.ajax({
type: "POST",
url: "getText.asmx/ws_getText",
data: parO1,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d.data);
}
, error: function () {
chyba("chyba v po?adavku", "df");
}
});
if (parO2.length > 0) {
$.ajax({
type: "POST",
url: "getText.asmx/ws_getText",
data: parO2,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
/*WAIT UNTIL THE FIRST CALL IS FINISHED AND THAN DO SOMETHING*/
}
, error: function () {
chyba("chyba v po?adavku", "df");
}
});
So any ideas? Thanks
那么有什么想法吗?谢谢
回答by Russ Cam
If using jQuery 1.5+, you can use jQuery.when()
to accomplish this. Something like (shortened the ajax calls for brevity, just pass the objects as you're doing above)
如果使用 jQuery 1.5+,您可以使用它jQuery.when()
来完成此操作。类似的东西(为简洁起见缩短了ajax调用,只需像上面那样传递对象)
$.when($.ajax("getText.asmx/ws_getText"),
$.ajax("getText.asmx/ws_getText")).done(function(a1, a2){
// a1 and a2 are arguments resolved for the
// first and second ajax requests, respectively
var jqXHR = a1[2]; // arguments are [ "success", statusText, jqXHR ]
});
You don't know in which order they will return so if you were rolling this by hand, you would need to check the state of the other request and wait until it has returned.
您不知道它们将按哪个顺序返回,因此如果您手动滚动它,则需要检查另一个请求的状态并等待它返回。
回答by Tejs
You need to wire up the second call to be contained within the callback of your first ajax call. Like so:
您需要将第二个调用连接到第一个 ajax 调用的回调中。像这样:
success: function(msg)
{
alert(msg.d.data);
if(par02.length > 0)
{
// Your 2nd ajax call
}
},
Since JavaScript doesnt run in multiple threads on the client, you can't block the thread until certain conditions are met.
由于 JavaScript 不会在客户端的多个线程中运行,因此在满足某些条件之前您不能阻塞线程。
回答by user3673557
Using jquery
使用jQuery
$.ajax({
type: "POST",
async:false, // ** CHANGED **
url: "getText.asmx/ws_getText",
data: parO1,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d.data);
}
, error: function () {
chyba("chyba v po?adavku", "df");
}
});
回答by latoyale
Here is another answer on running dual ajax requests. Like Tejs, the user makes an ajax call within the success method...
这是关于运行双 ajax 请求的另一个答案。与 Tejs 一样,用户在成功方法中进行 ajax 调用...
The poster states You're better off having the success method launch a new ajax request.."
海报说你最好让成功方法启动一个新的 ajax 请求......”