admin管理员组文章数量:1291014
I have the following function:
$.each(friends, function(friend, data) {
var group = "Chat";
$.ajax({'type':'GET', 'url':'/site/getgroup?username=' + friend,
'success':function(callback){
group = callback;
self.addFriend(friend, data.status, group);
}, //ajax success
}); //ajax
});
After these codes, I have some codes to initialize the chatBar using the Data from these .each and .ajax. However, right now since Ajax is async, it bees very buggy. How can I know that these .each are all finished with the returned ajax value without setting ajax async to false? (Means this part is pletely finished).
Like is there a way I can use .promise, plete, or XHRs to know the whole .each thing is plete? I tried out lots of stuff but they seem not to work for me.
Thank you,
I have the following function:
$.each(friends, function(friend, data) {
var group = "Chat";
$.ajax({'type':'GET', 'url':'/site/getgroup?username=' + friend,
'success':function(callback){
group = callback;
self.addFriend(friend, data.status, group);
}, //ajax success
}); //ajax
});
After these codes, I have some codes to initialize the chatBar using the Data from these .each and .ajax. However, right now since Ajax is async, it bees very buggy. How can I know that these .each are all finished with the returned ajax value without setting ajax async to false? (Means this part is pletely finished).
Like is there a way I can use .promise, .plete, or XHRs to know the whole .each thing is plete? I tried out lots of stuff but they seem not to work for me.
Thank you,
Share Improve this question asked Sep 20, 2013 at 15:17 jackhaojackhao 3,8574 gold badges23 silver badges44 bronze badges 1-
I would approach that in a different way by making one Ajax request only and loop through the results in the callback. Although that solution might require some refactoring of
getgroup
. – Mina Commented Sep 20, 2013 at 15:33
3 Answers
Reset to default 12Use $.when()
var xhrs = []
$.each(friends, function (friend, data) {
var group = "Chat";
var xhr = $.ajax({
'type': 'GET',
'url': '/site/getgroup?username=' + friend,
'success': function (callback) {
group = callback;
self.addFriend(friend, data.status, group);
}, //ajax success
}); //ajax
xhrs.push(xhr)
});
$.when.apply($, xhrs).done(function(){
//all are plete
});
A simple solution is to have a status array and for each ajax request, on success/error handler to update & check the status array to see if all other ajax requests have finished. This way, you can store also the response for each ajax request.
Take a look at $.when()
as it looks like it might solve your problem. I can't say for sure what it will do to $.each
.
http://api.jquery./jQuery.when/
版权声明:本文标题:javascript - Jquery ajax inside .each How to trigger function when the whole .each is complete - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741513732a2382760.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论