I have a for loop statement, each loop will execute an ajax call.
$.each(arr, function(i, v) {
var url = '/xml.php?id=' + v;
$.ajax({
url: url,
type: 'GET',
dataType: 'xml',
success: function(xml) {
if ($(xml).find('Lists').attr('total') == 1) {
// some code here
}
},
complete: function() {
// some code here
}
})
})
I want to run code after all ajax call completed under the loop, I have tried to place the code below to last line, it is not executed when the ajax call completed
if (i == arr.length - 1) {
// some code here
}
Therefore, if I have 10 times of loop, there are 10 times of ajax call. I want to run a code after there 10 times of ajax call completed, any ideas?
Is it better to use .ajaxComplete() or .done() to achieve it?
Thanks
Try using $.when()
var arr = [];
$.each(arr, function(i, v) {
var url = '/xml.php?id=' + v;
var xhr = $.ajax({
url: url,
type: 'GET',
dataType: 'xml',
success: function(xml) {
if ($(xml).find('Lists').attr('total') == 1) {
// some code here
}
},
complete: function() {
// some code here
}
});
arr.push(xhr);
})
$.when.apply($, arr).then(function(){
console.log('do')
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With