我如何让一个函数等待,直到所有的jQuery Ajax请求在另一个函数内完成?
简而言之,在执行下一个Ajax请求之前,我需要等待所有Ajax请求都完成。但如何?
我如何让一个函数等待,直到所有的jQuery Ajax请求在另一个函数内完成?
简而言之,在执行下一个Ajax请求之前,我需要等待所有Ajax请求都完成。但如何?
当前回答
Javascript是基于事件的,所以你不应该等待,而应该设置钩子/回调
你可以只使用jquery.ajax的success/complete方法
或者你可以使用。ajaxcomplete:
$('.log').ajaxComplete(function(e, xhr, settings) {
if (settings.url == 'ajax/test.html') {
$(this).text('Triggered ajaxComplete handler.');
//and you can do whatever other processing here, including calling another function...
}
});
虽然你应该张贴一个伪代码你的(s) ajax请求(s)是(是)被调用更精确…
其他回答
如果从头开始,我强烈建议使用$.when()。
尽管这个问题有超过一百万个答案,但我仍然没有找到任何对我的情况有用的答案。假设您必须处理现有的代码库,已经进行了一些ajax调用,并且不想引入承诺的复杂性和/或重做整个事情。
我们可以很容易地利用jQuery的.data, .on和.trigger函数,这些函数一直是jQuery的一部分。
Codepen
我的解决方案的优点是:
显然回调依赖于什么 函数triggerNowOrOnLoaded并不关心数据是否已经加载或我们仍在等待它 将其插入现有代码非常容易
$(function() { // wait for posts to be loaded triggerNowOrOnLoaded("posts", function() { var $body = $("body"); var posts = $body.data("posts"); $body.append("<div>Posts: " + posts.length + "</div>"); }); // some ajax requests $.getJSON("https://jsonplaceholder.typicode.com/posts", function(data) { $("body").data("posts", data).trigger("posts"); }); // doesn't matter if the `triggerNowOrOnLoaded` is called after or before the actual requests $.getJSON("https://jsonplaceholder.typicode.com/users", function(data) { $("body").data("users", data).trigger("users"); }); // wait for both types triggerNowOrOnLoaded(["posts", "users"], function() { var $body = $("body"); var posts = $body.data("posts"); var users = $body.data("users"); $body.append("<div>Posts: " + posts.length + " and Users: " + users.length + "</div>"); }); // works even if everything has already loaded! setTimeout(function() { // triggers immediately since users have been already loaded triggerNowOrOnLoaded("users", function() { var $body = $("body"); var users = $body.data("users"); $body.append("<div>Delayed Users: " + users.length + "</div>"); }); }, 2000); // 2 seconds }); // helper function function triggerNowOrOnLoaded(types, callback) { types = $.isArray(types) ? types : [types]; var $body = $("body"); var waitForTypes = []; $.each(types, function(i, type) { if (typeof $body.data(type) === 'undefined') { waitForTypes.push(type); } }); var isDataReady = waitForTypes.length === 0; if (isDataReady) { callback(); return; } // wait for the last type and run this function again for the rest of the types var waitFor = waitForTypes.pop(); $body.on(waitFor, function() { // remove event handler - we only want the stuff triggered once $body.off(waitFor); triggerNowOrOnLoaded(waitForTypes, callback); }); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body>Hi!</body>
正如其他答案所提到的,你可以使用ajaxStop()等待直到所有ajax请求完成。
$(document).ajaxStop(function() {
// This function will be triggered every time any ajax request is requested and completed
});
如果你想为特定的ajax()请求做这件事,你能做的最好的是在特定的ajax请求中使用complete()方法:
$.ajax({
type: "POST",
url: "someUrl",
success: function(data) {
// This function will be triggered when ajax returns a 200 status code (success)
},
complete: function() {
// This function will be triggered always, when ajax request is completed, even it fails/returns other status code
},
error: function() {
// This will be triggered when ajax request fail.
}
});
但是,如果你只需要等待几个和特定的ajax请求被完成?使用美妙的javascript承诺等待,直到这些ajax你想等待完成。我做了一个简单易读的示例,向您展示promises如何与ajax一起工作。请看下一个例子。我使用setTimeout来阐明这个示例。
// Note: // resolve() is used to mark the promise as resolved // reject() is used to mark the promise as rejected $(document).ready(function() { $("button").on("click", function() { var ajax1 = new Promise((resolve, reject) => { $.ajax({ type: "GET", url: "https://miro.medium.com/max/1200/0*UEtwA2ask7vQYW06.png", xhrFields: { responseType: 'blob'}, success: function(data) { setTimeout(function() { $('#image1').attr("src", window.URL.createObjectURL(data)); resolve(" Promise ajax1 resolved"); }, 1000); }, error: function() { reject(" Promise ajax1 rejected"); }, }); }); var ajax2 = new Promise((resolve, reject) => { $.ajax({ type: "GET", url: "https://cdn1.iconfinder.com/data/icons/social-media-vol-1-1/24/_github-512.png", xhrFields: { responseType: 'blob' }, success: function(data) { setTimeout(function() { $('#image2').attr("src", window.URL.createObjectURL(data)); resolve(" Promise ajax2 resolved"); }, 1500); }, error: function() { reject(" Promise ajax2 rejected"); }, }); }); var ajax3 = new Promise((resolve, reject) => { $.ajax({ type: "GET", url: "https://miro.medium.com/max/632/1*LUfpOf7teWvPdIPTBmYciA.png", xhrFields: { responseType: 'blob' }, success: function(data) { setTimeout(function() { $('#image3').attr("src", window.URL.createObjectURL(data)); resolve(" Promise ajax3 resolved"); }, 2000); }, error: function() { reject(" Promise ajax3 rejected"); }, }); }); Promise.all([ajax1, ajax2, ajax3]).then(values => { console.log("We waited until ajax ended: " + values); console.log("My few ajax ended, lets do some things!!") }, reason => { console.log("Promises failed: " + reason); }); // Or if you want wait for them individually do it like this // ajax1.then(values => { // console.log("Promise 1 resolved: " + values) // }, reason => { // console.log("Promise 1 failed: " + reason) // }); }); }); img { max-width: 200px; max-height: 100px; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button>Make AJAX request</button> <div id="newContent"> <img id="image1" src=""> <img id="image2" src=""> <img id="image3" src=""> </div>
我找到了一个很好的答案,这正是我在寻找的:)
jQuery ajaxQueue
//This handles the queues
(function($) {
var ajaxQueue = $({});
$.ajaxQueue = function(ajaxOpts) {
var oldComplete = ajaxOpts.complete;
ajaxQueue.queue(function(next) {
ajaxOpts.complete = function() {
if (oldComplete) oldComplete.apply(this, arguments);
next();
};
$.ajax(ajaxOpts);
});
};
})(jQuery);
然后你可以像这样向队列添加一个ajax请求:
$.ajaxQueue({
url: 'page.php',
data: {id: 1},
type: 'POST',
success: function(data) {
$('#status').html(data);
}
});
使用ajaxStop事件。
例如,假设你有一个载入…消息,同时获取100个ajax请求,你想隐藏该消息一旦加载。
jQuery文档:
$("#loading").ajaxStop(function() {
$(this).hide();
});
请注意,它将等待所有ajax请求在该页面上完成。
我的解决方案如下
var request;
...
'services': {
'GetAddressBookData': function() {
//This is the primary service that loads all addressbook records
request = $.ajax({
type: "POST",
url: "Default.aspx/GetAddressBook",
contentType: "application/json;",
dataType: "json"
});
},
...
'apps': {
'AddressBook': {
'data': "",
'Start': function() {
...services.GetAddressBookData();
request.done(function(response) {
trace("ajax successful");
..apps.AddressBook.data = response['d'];
...apps.AddressBook.Filter();
});
request.fail(function(xhr, textStatus, errorThrown) {
trace("ajax failed - " + errorThrown);
});
工作得很顺利。我已经尝试了许多不同的方法,但我发现这是最简单和最可重用的方法。希望能有所帮助