多个XHR请求进度跟踪

时间:2014-11-28 02:34:28

标签: javascript

5请求正在进行中。如果我们采用event.loaded,则每次从随机5个进度事件中显示备用值。我们如何针对每个xhr请求?

var xhr = [];

for (i = 0; i < 5; i++) {
  (function(i) {
    var start = new Date().getTime();
    xhr[i] = new XMLHttpRequest();
    url = "/" + "?n=" + Math.random();
    xhr[i].open("POST", url, true);
    xhr[i].setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    xhr[i].upload.addEventListener("progress", progressHandler, false);

    function progressHandler(event) {
      end = new Date().getTime();
      time = (end - start) / 1000;
      var duration = time;
      var bytes = event.loaded;
    }
  };
  xhr[i].send(UploadData);

1 个答案:

答案 0 :(得分:0)

这是因为您对所有5个进程使用相同的处理程序,每个进程都需要单独的处理程序。然后,您可以使用共享范围来计算总体进度:

var xhr = [];
var progress = [];


for (i = 0; i < 5; i++) {
  (function(i) {
    var start = new Date().getTime();
    xhr[i] = new XMLHttpRequest();
    url = "/" + "?n=" + Math.random();
    xhr[i].open("POST", url, true);
    xhr[i].setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    xhr[i].upload.addEventListener("progress", createProgressHandler(start, i), false);
    xhr[i].send(UploadData);
    // Initialize progress:
    progress[i] = { bytes: 0 };
};

function createProgressHandler(start, i) {
    return function (event) {
      end = new Date().getTime();
      time = (end - start) / 1000;
      var duration = time;
      var bytes = event.loaded;

      progress[i].bytes = bytes;

      console.log('Event from upload #' + i + ', bytes loaded: ' + bytes);
    }
}