如何使jQuery的Ajax的负载要求真正的进度条? [英] How to make real progress bar of jQuery Ajax load request?
问题描述
我需要的是一个动画的进度条(像一个在YouTube上)但请无插件!
What I need is an animated progress bar (like the one on youtube) BUT please no plugins!
我的Ajax请求是这样的:
My ajax request looks like this:
$.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,我在progress事件的工作。
So, I have an animation already made but I could not link it to be real, this is a static animation but I'm not able to make it work with the precentComplete that I have in the progress event.
任何想法吗?我需要在这个XHR2更多的澄清工作片段或例子更好地理解。
Any ideas please? I need more clarification on this XHR2 with working snippet or example for better understanding.
动画看起来是这样的:的jsfiddle
The animation looks like this :jsFiddle
推荐答案
我的第一个镜头是定义进度栏的进步的事件处理程序之外,然后只从事件处理程序中设置了width属性。
My first shot would be to define the progress bar outside the 'progress' event handler, and then only set the width property from within the event handler.
$.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页面下载进度
这篇关于如何使jQuery的Ajax的负载要求真正的进度条?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!