我如何让一个函数等待,直到所有的jQuery Ajax请求在另一个函数内完成?
简而言之,在执行下一个Ajax请求之前,我需要等待所有Ajax请求都完成。但如何?
我如何让一个函数等待,直到所有的jQuery Ajax请求在另一个函数内完成?
简而言之,在执行下一个Ajax请求之前,我需要等待所有Ajax请求都完成。但如何?
当前回答
正如其他答案所提到的,你可以使用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>
其他回答
看看我的解决方案:
1.将这个函数(和变量)插入到你的javascript文件:
var runFunctionQueue_callback;
function runFunctionQueue(f, index, callback) {
var next_index = index + 1
if (callback !== undefined) runFunctionQueue_callback = callback;
if (f[next_index] !== undefined) {
console.log(index + ' Next function avalaible -> ' + next_index);
$.ajax({
type: 'GET',
url: f[index].file,
data: (f[index].data),
complete: function() {
runFunctionQueue(f, next_index);
}
});
} else {
console.log(index + ' Last function');
$.ajax({
type: 'GET',
url: f[index].file,
data: (f[index].data),
async: false,
complete: runFunctionQueue_callback
});
}
}
2.用你的请求构建一个数组,像这样:
var f = [
{file: 'file_path', data: {action: 'action', data: 'any_data}},
{file: 'file_path', data: {action: 'action', data: 'any_data}},
{file: 'file_path', data: {action: 'action', data: 'any_data}},
{file: 'file_path', data: {action: 'action', data: 'any_data}}
];
3.创建回调函数:
function Function_callback() {
alert('done');
}
4.使用参数调用runFunctionQueue函数:
runFunctionQueue(f, 0, QuestionInsert_callback);
// first parameter: array with requests data
// second parameter: start from first request
// third parameter: the callback function
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)是(是)被调用更精确…
如果您想知道文档中所有ajax请求何时完成,无论它们有多少,只需使用$。ajaxStop事件如下所示:
$(document).ajaxStop(function () {
// 0 === $.active
});
在这种情况下,您既不需要猜测应用程序中发生了多少请求(这些请求可能在将来完成),也不需要深入研究函数的复杂逻辑或查找哪些函数正在执行HTTP(S)请求。 美元。这里的ajaxStop也可以绑定到任何HTML节点 认为可以按要求修改。
更新: 如果您想坚持使用ES语法,那么可以使用Promise。所有已知的ajax方法:
Promise.all([ajax1(), ajax2()]).then(() => {
// all requests finished successfully
}).catch(() => {
// all requests finished but one or more failed
})
这里有趣的一点是,它同时适用于Promises和$。ajax请求。
下面是jsFiddle演示。
更新2: 使用async/await语法的最新版本:
try {
const results = await Promise.all([ajax1(), ajax2()])
// do other actions
} catch(ex) { }
使用ajaxStop事件。
例如,假设你有一个载入…消息,同时获取100个ajax请求,你想隐藏该消息一旦加载。
jQuery文档:
$("#loading").ajaxStop(function() {
$(this).hide();
});
请注意,它将等待所有ajax请求在该页面上完成。
一个小小的变通方法是这样的:
// Define how many Ajax calls must be done
var ajaxCalls = 3;
var counter = 0;
var ajaxCallComplete = function() {
counter++;
if( counter >= ajaxCalls ) {
// When all ajax calls has been done
// Do something like hide waiting images, or any else function call
$('*').css('cursor', 'auto');
}
};
var loadPersons = function() {
// Show waiting image, or something else
$('*').css('cursor', 'wait');
var url = global.ctx + '/loadPersons';
$.getJSON(url, function(data) {
// Fun things
})
.complete(function() { **ajaxCallComplete();** });
};
var loadCountries = function() {
// Do things
var url = global.ctx + '/loadCountries';
$.getJSON(url, function(data) {
// Travels
})
.complete(function() { **ajaxCallComplete();** });
};
var loadCities = function() {
// Do things
var url = global.ctx + '/loadCities';
$.getJSON(url, function(data) {
// Travels
})
.complete(function() { **ajaxCallComplete();** });
};
$(document).ready(function(){
loadPersons();
loadCountries();
loadCities();
});
希望能有用…