我有一个简单的表单,它在提交时通过ajax请求进行验证。如果表单签出ok,则发出另一个ajax请求来处理最初提交的数据。
我想为此建立一个进度条。我发现将此代码添加到每个ajax请求分别返回每个调用的进度。这使得进度条负载达到100%,两倍,快速。
例如,两个ajax请求是否可以分别填充50%的进度条?那么ajax请求1将填充高达50%,而第二个将填充从51%到100%?还是说这很疯狂?
或者,如果三个ajax调用分别负责33.33%的总百分比?
我想我们更多的是着眼于完成的阶段和进展。
有什么办法可以做到这一点,而不用太多的伪装呢?
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with upload progress
console.log('percent uploaded: ' + (percentComplete * 100));
}
}, false);
//Download progress
xhr.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with download progress
console.log('percent downloaded: ' + (percentComplete * 100));
}
}, false);
return xhr;
发布于 2016-07-03 10:30:08
是的,这是可能的。您可以创建一个包含每个ajax调用的数组。将<progress>
元素max
属性设置为100/array.length
。将单个progress
事件的progress
除以数组.length
设置<progress>
元素的value
。您还可以使用Promise.all()
、.then()
处理从ajax调用返回Promise
的函数数组,并更新<progress>
元素。
html
<label></label>
<progress value="0" min="0" max="100"></progress>
javascript
var progress = document.querySelector("progress");
var url = "/echo/html/";
function request(url) {
var len = arr.length;
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = ((evt.loaded / evt.total) * (progress.max / len))
/ len;
progress.value += percentComplete;
console.log(progress.value, percentComplete);
if (evt.total === evt.loaded) {
requests += 1;
}
if (progress.value == progress.max && requests === len) {
progress.previousElementSibling.innerHTML = "upload complete";
// you could call `resolve()` here if only interested in
// `upload` portion of request
alert("upload complete");
}
}
}, false);
xhr.onload = function() {
resolve(this.responseText)
};
xhr.onerror = reject;
xhr.open("POST", url, true)
xhr.send("html=" + Array(100000).fill(1).join(""));
})
}
var arr = [], requests = 0;
arr.push(request, request, request);
Promise.all(arr.map(function(req) {
return req(url)
}))
.then(function(data) {
console.log(data);
})
.catch(function(err) {
console.log(err)
})
jsfiddle https://jsfiddle.net/v2msL7hj/3/
发布于 2016-07-03 10:37:38
好吧,我创建这样一个进度条的方式是,因为您希望每个函数都被一个接一个地调用,也就是说,一个函数的完成应该触发另一个函数,所以XMLHttpRequest有一个状态变化事件。您可以使用该事件确认第一个请求是否成功执行,然后触发第二个请求,在每次更改时,进度条将以您想要的任何%递增。
function postdata()
{
var xhr = new XMLHttpRequest();
xhr.open
(
"POST",
Url,
true
);
xhr.send();
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4)
{
//Call next function here and increment progressbar
}
}
}
希望这能帮上忙
https://stackoverflow.com/questions/38172978
复制