我有一个函数可以调用其他具有 AJAX 请求的函数。我希望所有 AJAX 调用在调用最后一个函数之前完成。我初始化一个数组,并需要在执行最后一步之前成功完成所有 AJAX 调用。当我在浏览器中运行代码时,控制台显示第一个 AJAX 调用完成之前调用的最后一个方法。我尝试过使用 .done
但我仍然得到相同的结果。
function Search() {
var userIds = [];
var certName = $('#certificationName').val();
var skillNumberOne = $('#skillName1').val();
var skillNumberTwo = $('#skillName2').val();
var skillNumberThree = $('#skillName3').val();
var locale = $('#location').val();
CertMatchResults(certName, userIds);
SkillMatchResults(skillNumberOne, userIds);
SkillMatchResults(skillNumberTwo, userIds);
SkillMatchResults(skillNumberThree, userIds);
LocationMatchResults(locale, userIds);
console.log(userIds);
DisplayMatches(userIds);
}
function CertMatchResults(certName, userIds) {
if (certName == '') return;
$.getJSON('json_data.php', { method: 'matchCerts', certName: certName }, function(data) {
$.each(data, function(key, value) {
console.log("Cert Match >>> " + value.user_id);
userIds.push(value.user_id);
});
}).done(function() {
console.log("Cert match completed.");
});
}
function SkillMatchResults(skillName, userIds) {
if (skillName == '') return;
$.getJSON('json_data.php', { method: 'matchSkill', skillName: skillName }, function(data) {
$.each(data, function(key, value) {
console.log("Skill Match >>> " + value.user_id);
userIds.push(value.user_id);
});
});
}
... other calls below ... I can add them if needed
DisplayMatches
需要每个函数中的所有 AJAX 调用才能完成。
最佳答案
您应该创建一个 deferred objects 链.
每个 ajax 调用都会返回 Deferred 对象,然后您可以将它们收集在 jQuery.when 中函数并在所有 ajax 调用解决了 jQuery.then 函数中的 promise 后调用最后一个函数。
$.when( $.getJson("url1"), $.getJson("url2") ).then(function( valueFromUrl1, valueFromUrl2 ) {
functionThatShouldBeInvokedLast();
});
关于javascript - 等待 AJAX 调用链完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32743618/