【问题标题】:Tracking multiple jquery ajax API requests with progress bar使用进度条跟踪多个 jquery ajax API 请求
【发布时间】:2021-01-27 13:03:44
【问题描述】:

我有一个增量,它接受 id 并将它们添加到 url 以发出多个 ajax 请求。
js:

for (x = 1; x <= val['id_count']; x++) {
 $.ajax({
    url: baseUrl + x,
    dataType: "json",
    success: function(results, status, xhr) {
   },
    error: function(xhr, status, error) {
    $("#message").html("data: " + status + " " + error)
   }
 })
}


HTML

<div class="progress">
    <div class="progress-bar" role="progressbar" style="width: 0%" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
</div>

我在这里尝试做的是计算 id(url)并显示请求的进度是进度条,看看完成的百分比和剩余的百分比。还有总共有多少个 id 以及总共完成了多少个请求。

另一方面,这是我想做的例如:

到目前为止我做了什么:

for (x = 1; x <= val['id_count']; x++) {
 totalIDs = 0;
 totalIDs = x.length;
 $.ajax({
    url: baseUrl + x,
    dataType: "json",
    xhr: function() {
      var xhr = new window.XMLHttpRequest();
      xhr.onreadystatechange = function() {
      var progress = x / totalIDs * 100;
      $(".progress-bar").css({
          "width": progress + "%"
        });
      }
     return xhr;
    },
    success: function(results, status, xhr) {
    },
    error: function(xhr, status, error) {
    $("#message").html("data: " + status + " " + error)
   }
 })
}

ps: 新手

【问题讨论】:

  • @RoryMcCrossan 好吧,有限制吗?它看起来很疯狂,但 api 并没有一次提供所有信息,所以我必须像这样循环通过它们,它有很多请求并且需要一些时间,所以我需要看看后台发生了什么。
  • 看看api.jquery.com/category/ajax/global-ajax-event-handlers - 你可以使用 .ajaxSend() 来增加“进行中”并使用 .ajaxComplete 来减少它
  • @freedomn-m 谢谢我确实读过这些东西,但我是新手,所以我需要更多的解释。
  • 看起来你可以将你的进度更新移动到success: 而不是xhr: - xhr: 有点高级,你不太可能需要使用它。你可以有一个var inprogress 然后inprogress++ 作为forinprogress--success 内的第一行并计算你的进度条位置var progress = (totalIDs - inprogress)/totalIDs * 100 (左右)
  • @freedomn-m 不幸的是它没有用。或者我犯了一个错误idk

标签: javascript jquery ajax twitter-bootstrap progress-bar


【解决方案1】:
for (x = 1; x <= val['id_count']; x++) {
 $.ajax({
    url: baseUrl + x,
    dataType: "json",
    success: function(results, status, xhr) {
       if (inprogress < total_urls) {
         inprogress++;
         $("#tProgress").html(inprogress + ' / ' + total_urls + ' ✓');
         progress = Math.round(inprogress / total_urls * 100);
         $("#progress-bar").css({
            "width": progress + "%"
         });
         $("#progress-bar").html(progress + '%');
       }
    },
    error: function(xhr, status, error) {
    $("#message").html("data: " + status + " " + error)
   }
 })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多