在 for 循环 javascript 结束时执行操作



我一直在尝试在 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 请求。但是,由于它们是异步的,因此不能保证它们在重定向之前已完成。

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

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

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

最新更新