jQuery $ when.apply().. then()为每个已完成的请求触发

时间:2013-12-18 21:04:02

标签: ajax jquery promise

这是我在ASP.NET MVC Razor视图中创建的jQuery方法。所需的功能是:

  • 选择textAreas
  • 触发一系列ajax请求
  • 所有ajax请求完成后,显示警告对话框

代码似乎正常工作,除了警报“ok”对话框多次显示,每次请求一次。这表明正在为每个请求调用.then()方法,而不是等待所有请求完成。我在这里做错了什么?

// Save changed entity notes
function saveChangedNotes() {

  var ajaxReqs = [];
  $('textarea').each(function() {
    ajaxReqs.push($.ajax({
        type: "POST",
        url: "@Url.Action("UpdateCompanyNote", "Company", new {companyId = Html.CompanyIdFromRouteValues()})",
        data: {
          noteId: this.id,
          noteText: $(this).val()
        }
      })
    );

    // When all ajax complete..
    $.when.apply($, ajaxReqs).then(function() {      
      alert('ok');
    }).fail(function() {         
      alert('error');
    });
  });
}

2 个答案:

答案 0 :(得分:5)

您在每个循环中执行textarea内的$.when.apply 。计算你的右括号。

答案 1 :(得分:1)

有一种更简单的替代方法可以在不使用$.when.apply和数组的情况下执行此操作

而是使用模式promise = $.when(promise, anotherPromise)

e.g。为你的例子这样的

// Save changed entity notes
function saveChangedNotes() {
    // Start with a resolved promise (undefined does the same thing for $.when!)
    var promise;
    $('textarea').each(function () {
        promise = $.when(promise, $.ajax({
            type: "POST",
            url: "@Url.Action("
            UpdateCompanyNote ", "
            Company ", new {companyId = Html.CompanyIdFromRouteValues()})",
            data: {
                noteId: this.id,
                noteText: $(this).val()
            }
        }));
    });
    // When all ajax complete..
    promise.then(function () {
        alert('ok');
    }).fail(function () {
        alert('error');
    });
}