当.each完成循环我的元素时,如何启动一个重定向到新页面的函数? 这是我目前的代码: $('#tabCurrentFriends .dragFriend').each(function(){ var friendId = $(this).data('rowid'); $.ajax({ type: "POST", url: "../.
这是我目前的代码:
$('#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){
}
});
});
在完成所有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 = 'https://stackoverflow.com/';
});
编辑 – 要使用数组时,必须使用apply:
$.when.apply(null, XHRs).then(function () {
window.location = 'https://stackoverflow.com/';
});
jQuery AJAX请求创建了在其完整函数触发时解析的deffered对象.此代码将这些被保护的对象存储在一个数组中,当它们全部解析了.then()内的函数时.
文档:
> $.when():http://api.jquery.com/jquery.when
> $.then():http://api.jquery.com/deferred.then/
