且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery完成时,触发函数

更新时间:2023-11-20 23:32:34

在完成所有AJAX请求之后,您可以使用$.when()/$.then()重定向用户:

You can use $.when()/$.then() to redirect your users after all the AJAX requests are done:

//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://***.com/';
});

编辑-要对数组使用when,必须使用apply:

Edit - to use when with an array, apply must be used:

$.when.apply(null, XHRs).then(function () {
    window.location = 'http://***.com/';
});

jQuery AJAX请求创建延迟对象,这些对象将在其完整功能触发时解析.这段代码将这些受延迟的对象存储在一个数组中,当它们全部解析后,.then()中的函数就会运行.

jQuery AJAX requests create deffered objects that resolve when their complete function fires. This code stores those deffered objects in an array and when they all resolved the function within .then() is run.

文档:

  • $.when(): http://api.jquery.com/jquery.when
  • $.then(): http://api.jquery.com/deferred.then/