本文介绍了一个函数中的所有ajax调用完成后,如何触发一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个问题要找出所有的ajax何时完成.这是我的功能.
I have a problem of finding when all the ajax completed.Here is my function.
function getValuesForTablePropertySelected(questionList, itemsArray) {
for (var i = 0; i < itemsArray.length; i++) {
switch (itemsArray[i]) {
case "Tags":
loadTag(questionList);
break;
case "Date Created":
displayTablePropertySelected(itemsArray);
break;
case "Date Last Used":
loadDLU(questionList);
break;
case "Number of Launched Surveys Used In":
loadNLSU(questionList);
break;
case "Number of Reponses":
loadNR(questionList);
break;
case "Type 1 Associations":
loadT1A(questionList);
break;
case "Type 3 Associations":
loadT3A(questionList);
break;
case "Sites Linked To":
loadSLT(questionList);
break;
case "Last Modified By":
displayTablePropertySelected(itemsArray)
break;
default:
break;
}
}
showResult();
}
案例"中的每个函数都包含一个ajax调用.我只需要使用异步调用.
Each function in the "CASE" contains an ajax call. I need to use asynchronous calls only.
我想在AJAX完成后在所有功能中触发"showResult()"功能.不同的AJAX需要花费不同的时间来完成.
I want to trigger "showResult()" function after AJAX complete in all the functions . Different AJAX is taking different time to complete.
请帮助我找到这种情况的解决方案.
Please help me find a solution for this situation.
推荐答案
您可以轻松地使用jQuery .ajaxComplete()
:
You can do it easily with jQuery .ajaxComplete()
:
// create a counter (global)
var ajax_calls_counter = 0;
// in your current code, in each ajax call success, add 1 to the counter
// manage ajax succeeded events
$(document).ajaxComplete(function(){
if( ajax_calls_counter == itemsArray.length ){
showResult();
}
});
示例( jsFiddle ):
$(function(){
$(this).ajaxComplete(function(){
var $body = $('body');
$body.append('ajax number '+ counter +' call complete!<br />');
if( counter == array.length ) $body.append('<strong>all</strong> ajax calls completed');
});
var array = [1, 2, 3, 4, 5];
var counter = 0;
for( var i = 0; i < array.length; i++ ){
$.ajax({
url: location.href,
success: function(){
counter++;
}
});
}
});
这篇关于一个函数中的所有ajax调用完成后,如何触发一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!