目前正在进行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);发布于 2014-11-28 04:01:58
这是因为对所有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);
}
}https://stackoverflow.com/questions/27181121
复制相似问题