【问题标题】:Perform action at end of for loop javascript [duplicate]在for循环javascript结束时执行操作[重复]
【发布时间】:2017-10-20 09:43:34
【问题描述】:

我一直在尝试在 for 循环完成后重定向页面,但即使代码在 for 循环之外,它也会在 for 循环之前执行它。所以我想知道在JavaScript中完成for循环后是否有某种方法可以执行代码并重定向到另一个页面。这是我的代码。

$('#submit').click(function(e) {
   e.preventDefault();
   var total = $('#total').val();

   for (var i = 0; i < total; i++) {
     if ($('#check_' + i).is(':checked')) {
       // The string to be posted to the submit file
       var dataString = 'month=' + month + '&year=' + year + '&patient_id=' + patient_id;

       // AJAX code to submit form.
       $.ajax({
         type: "POST",
         url: "pages/views/payroll/bulk_payroll_functions.php",
         data: dataString,
         cache: false,
         success: function(result) {
           alert("good");
         }
       });
     }
   }
   alert("All members payrolls made");
   window.location = ("index.php?lang=en&page=view_payroll");
})

【问题讨论】:

  • $.ajax 是异步的,它不会妨碍您的外观。快速、简单、肮脏的解决方法是添加选项async: false。正确的解决方案是重新编码处理异步性的示例。
  • @Booster2ooo:为什么不将其发布为答案?
  • 而不是在 foreach 内部运行 ajax。您可以将数据制作为数组并一次性处理所有内容。
  • @Booster2ooo,感谢您的提示。添加 async: false 修复了它,现在可以正常工作了。
  • async: false 已弃用,不应使用。它现在已经“修复”了,但是您阻止了 UI,并且将来可能会破坏代码。

标签: javascript


【解决方案1】:

代码正在按您的预期工作 - 正在发出 AJAX 请求。 然而,因为它们是异步的,你不能保证它们在你重定向之前已经完成。

最干净的方法是使用 $.ajax 返回的 Promise。

当所有 ajax 请求完成后,您可以使用$.when 重定向:

$('#submit').click( function(e) {
  e.preventDefault();

  // array to store the promises
  var promises = [];

  var total = $('#total').val();

  for(var i = 0; i < total; i++){
    if($('#check_' + i).is(':checked')){
      // The string to be posted to the submit file
      var dataString = 'month=' + month + '&year=' + year + '&patient_id=' + patient_id ;

      // AJAX code to submit form.
      promise = $.ajax({
        type: "POST",
        url: "pages/views/payroll/bulk_payroll_functions.php",
        data: dataString,
        cache: false,
        success: function (result) {
          alert("good");
        }
      });

      // add ajax request to the promises
      promises.push(promise);
    }
  }

  // redirect when all promises have resolved
  $.when(promises).then(function () {
    alert("All members payrolls made");
    window.location = ("index.php?lang=en&page=view_payroll");
  });
});

【讨论】:

  • 我只是建议使用原生 Promises 而不是 jQuery 实现。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多