当.each完成循环我的元素时,如何启动一个重定向到新页面的函数? 这是我目前的代码:
$('#tabCurrentFriends > .dragFriend').each(function(){
var friendId = $(this).data('rowid');
$.ajax({
type: "POST", url: "../../page/newtab.php", data: "action=new&tabname=" + tabname + "&bid=" + brugerid + "&fid=" + friendid,
complete: function(data){
}
});
});
答案 0 :(得分:13)
在完成所有AJAX请求后,您可以使用$.when()
/ $.then()
重定向用户:
//create array to hold deferred objects
var XHRs = [];
$('#tabCurrentFriends > .dragFriend').each(function(){
var friendId = $(this).data('rowid');
//push a deferred object onto the `XHRs` array
XHRs.push($.ajax({
type: "POST", url: "../../page/newtab.php", data: "action=new&tabname=" + tabname + "&bid=" + brugerid + "&fid=" + friendid,
complete: function(data){
}
}));
});
//run a function when all deferred objects resolve
$.when(XHRs).then(function (){
window.location = 'http://stackoverflow.com/';
});
修改 - 要将when
与数组一起使用,必须使用apply
:
$.when.apply(null, XHRs).then(function () {
window.location = 'http://stackoverflow.com/';
});
jQuery AJAX请求创建在其完整函数触发时解析的deffered对象。此代码将这些被保护的对象存储在一个数组中,当它们全部解析后,.then()
内的函数就会运行。
文档:
$.when()
:http://api.jquery.com/jquery.when $.then()
:http://api.jquery.com/deferred.then/ 答案 1 :(得分:5)
AJAX是异步发生的,所以你必须尝试这样的事情:
var total = $('#tabCurrentFriends > .dragFriend').length;
var completed = 0;
$('#tabCurrentFriends > .dragFriend').each(function(){
var friendId = $(this).data('rowid');
$.ajax({
type: "POST", url: "../../page/newtab.php", data: "action=new&tabname=" + tabname + "&bid=" + brugerid + "&fid=" + friendid,
complete: function(data){
completed++;
if (completed == total) {
// All have been loaded.
}
}
});
});