显示JSON数据的下载进度百分比

时间:2015-08-26 13:22:34

标签: javascript jquery ajax json

$.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具有内容长度标题。

还有其他方法可以跟踪JSON数据的实时下载进度吗?

1 个答案:

答案 0 :(得分:1)

根据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")
    }
});