使用ajax调用在每个循环后调用一个函数

时间:2018-04-27 20:55:58

标签: javascript jquery promise

我有一个循环,我正在制作一个ajax帖子。我想执行函数" doSomething()"只有在我的循环(以及每个循环内的ajax帖子)完成之后。

我认为这被称为承诺,但我只是在完成服务器端后才进入jQuery ...



 selectedRows.each(function(e) {
            var dataforpost = { groupId: selectedGroup.Id, 
            userName: userName, displayName: displayName };

            $.ajax({
                url: '@Url.Action("AddMemberToGroup")',
                type: "POST",
                data: dataforpost,
                success: function(data) {}
            });
        });
        
  // now when that loop is done, do something
  doSomething();




2 个答案:

答案 0 :(得分:1)

您可以使用$.when

$.when(selectedRows.each(function(e) {
  var dataforpost = { groupId: selectedGroup.Id, 
  userName: userName, displayName: displayName };

  $.ajax({
    url: '@Url.Action("AddMemberToGroup")',
    type: "POST",
    data: dataforpost,
    success: function(data) {}
  });
})).then(function() {
  // now when that loop is done, do something
  doSomething();
});

或者您可以跟踪最后一个循环并触发done函数调用:

selectedRows.each(function(i, e) {
  var dataforpost = { groupId: selectedGroup.Id, 
  userName: userName, displayName: displayName };

  $.ajax({
    url: '@Url.Action("AddMemberToGroup")',
    type: "POST",
    data: dataforpost,
    success: function(data) {},
    done: function() {
      if (i == selectedRows.length - 1) {
        // now when that loop is done, do something
        doSomething();
      }
    }
  });
});

答案 1 :(得分:0)

Perharps帮助:

  selectedRows.each(function(index, elem) {
        var dataforpost = { groupId: selectedGroup.Id, 
        userName: userName, displayName: displayName };

        var jqxhr = $.ajax({
            url: '@Url.Action("AddMemberToGroup")',
            type: "POST",
            data: dataforpost,
            success: function(data) {}
        });
        jqxhr.then(function() {
          console.log( index );
          if ((index+1) >= selectedRows.length){
             console.log('last');
             // now when that loop is done, do something
             doSomething();
          }
        });
    });