$.ajax({
url: 'https://www.udacity.com/public-api/v0/courses',
xhr: function () {
console.log('xhr');
var xhr = new XMLHttpRequest();
xhr.addEventListener('loadend', uploadComplete, false);
function uploadComplete(event) {
console.log('uploadComplete');
}
xhr.addEventListener("progress", function (evt) {
console.log(evt.percentComplete);
console.log([evt.lengthComputable, evt.loaded, evt.total]);
// if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
console.log(percentComplete + "p")
//}
}, false);
return xhr;
},
success: function (response) {
console.log("success")
}
});
对于上面的代码,我在控制台中得到的输出如下:
script.js:15 [false, 22463, 0]
script.js:18 Infinityp
script.js:14 undefined
script.js:15 [false, 53062, 0]
script.js:18 Infinityp
script.js:14 undefined
script.js:15 [false, 85830, 0]
script.js:18 Infinityp
script.js:14 undefined
script.js:15 [false, 124733, 0]
script.js:18 Infinityp
script.js:14 undefined
......
为什么 evt.lengthComputable 显示为 false 而 evt.total 显示为 0 ? P.S:URL 具有内容长度 header 。
是否有其他方法可以跟踪 JSON 数据的实时下载进度?
最佳答案
根据this SO answer您应该将 eventlisteners
添加到 xhr 对象的 upload
属性中。所以你的代码应该是这样的:
$.ajax({
url: 'https://www.udacity.com/public-api/v0/courses',
xhr: function () {
console.log('xhr');
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('loadend', uploadComplete, false); // <-- CHANGED LINE
function uploadComplete(event) {
console.log('uploadComplete');
}
xhr.upload.addEventListener("progress", function (evt) { // <-- CHANGED LINE
console.log(evt.percentComplete);
console.log([evt.lengthComputable, evt.loaded, evt.total]);
var percentComplete = (evt.loaded / evt.total) * 100;
console.log(percentComplete + "p")
}, false);
return xhr;
},
success: function (response) {
console.log("success")
}
});
关于javascript - 显示 JSON 数据的下载进度百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32227873/