当.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){
}
});
});
Run Code Online (Sandbox Code Playgroud)
Jas*_*per 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/';
});
Run Code Online (Sandbox Code Playgroud)
编辑 - 要when与数组一起使用,apply必须使用:
$.when.apply(null, XHRs).then(function () {
window.location = 'http://stackoverflow.com/';
});
Run Code Online (Sandbox Code Playgroud)
jQuery AJAX请求创建了在其完整函数触发时解析的deffered对象.此代码将这些被保护的对象存储在一个数组中,当它们全部解析后,运行内部的函数.then().
文档:
$.when():http://api.jquery.com/jquery.when$.then():http://api.jquery.com/deferred.then/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.
}
}
});
});
Run Code Online (Sandbox Code Playgroud)