首页 > 解决方案 > 进行多个同步 AJAX 调用并显示状态

问题描述

我有一个 for 循环,在其中我使用键进行 AJAX 调用并将结果附加到表中。每次通话后,我都会触发一个进度条。当我进行异步调用时,它会在 5-6 次调用后冻结并且没有响应。如果我使呼叫同步,它会完美运行,但这次我无法在进度条上显示状态,因为它会冻结页面。

$("#btn-fetch").on("click", function() {
  var starts = $('#starts').val();
  var ends = $('#ends').val();
  var howmany = ends - start + 1;

  $('#progress-text').html('<strong>%0</strong>');
  $('#progress-status').css('width', '0%');
  var percent = 100 / howmany;
  var progress_status = 0;

  for (var i = start; i <= ends; i++) {
    $.ajax({
      url: 'fetch.php',
      data: {
        id: i
      },
      type: "POST",
      //async: false,
      success: function(data) {
        console.log(data);
        $("#table-body").append(data);
        progress_status += percent;
        $('#progress-text').html('<strong>%' + progress_status.toFixed(2) + '</strong>');
        $('#progress-status').css('width', progress_status.toFixed(2) + '%'); -
      },
      error: function(err) {
        console.log(err) // Reject the promise and go to catch()
      }
    });
  }
})

标签: javascriptphpjqueryajax

解决方案


推荐阅读