我需要的是一个动画进度条(就像 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/