javascript - 如何制作 jQuery Ajax 加载请求的真正进度条?

标签 javascript jquery css ajax html

我需要的是一个动画进度条(就像 youtube 上的那样),但请不要使用插件!

我的 ajax 请求是这样的:

$.ajax({
    xhr: function() {
        var xhr = new window.XMLHttpRequest();
        //Download progress
        xhr.addEventListener("progress", function(evt) {
            if (evt.lengthComputable) {
                console.log(evt);
                var percentComplete = evt.loaded / evt.total * 100;
                //Do something with download progress
                // this is a static animation but i'm not able to make it work with the precentComplete that i have.
                $({
                    property: 0
                }).animate({
                    property: 105
                }, {
                    duration: 4000,
                    step: function() {
                        var _percent = Math.round(this.property);
                        $('#progress').css('width', _percent + "%");
                        if (_percent == 105) {
                            $("#progress").addClass("done");
                        }
                    },
                    complete: function() {
                        alert('complete');
                    }
                });
            }
        }, false);
        return xhr;
    },
    type: method,
    url: rest_api,
    headers: headers,
    timeout: 10000,
    dataType: 'json',
    data: http_content,
    beforeSend: function(xhr) {
        // do stuff
    },
    success: function(data, status, xhr) {
        // do stuff
    },
    error: function(xhr, e) {
        // do stuff
    }
});

所以,我已经制作了一个动画,但我无法将其链接为真实动画,这是一个静态动画,但我无法使其与进度事件中的 precentComplete 一起使用。

有什么想法吗?我需要使用工作片段或示例对此 XHR2 进行更多说明,以便更好地理解。

动画看起来像这样:jsFiddle

最佳答案

我的第一步是在“进度”事件处理程序之外定义进度条,然后仅在事件处理程序内设置宽度属性。

$.ajax({
    xhr: function() {
        var xhr = new window.XMLHttpRequest();
        var progressBar = $("#progress");

        //Download progress
        xhr.addEventListener("progress", function(evt) {
            if (evt.lengthComputable) {
                console.log(evt);
                var percentComplete = /* compute it */;
                progressBar.style("width", percentComplete + "%");
            }
        }, false);
        return xhr;
    },
    ...
});

似乎并不是每个浏览器都允许您轻松跟踪下载进度,您可以在此处找到有关如何实际计算进度的更多信息:AJAX Page Download progress

关于javascript - 如何制作 jQuery Ajax 加载请求的真正进度条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31006798/

相关文章:

javascript - 点击 li 应该在其他 div 中打开一个 url 但有一些数据

javascript - 我的 jquery 加载了两次吗?

javascript - Firebase 身份验证,未定义 firebase

javascript - Alias ES6 解构

jquery - Phonegap android 上的可拖动 jQuery

javascript - 滚动到元素时执行 FadeInUp 动画(javascript)

javascript - Vue.js 无法使用模板正确渲染

javascript - 提交 jquery 表单而不会过早关闭窗口?

javascript - Jquery加载到div中,指定链接数据中的div

javascript - 如何在鼠标悬停时更改 setInterval() 回调函数不断修改的元素的值?