jQuery when each is completed, trigger function

孤街浪徒 提交于 2019-11-26 09:59:50

问题


how do start a function like redirecting to a new page when .each is done looping my elements? this is my current code:

$(\'#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){
        }
    });
});

回答1:


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

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

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

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.

Docs:

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



回答2:


AJAX happens asynchronously, so you'll have to try something like this:

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.
              }
        }
    });
});


来源:https://stackoverflow.com/questions/8460172/jquery-when-each-is-completed-trigger-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!