我想在执行 ajax
请求时使用 bootstrap 制作一个 进度条
。我可以启动进度条,但问题是当 ajax 调用
成功成功
时,我不知道如何让它停止在 100%。以下是我编写的代码:
html
<div class="progress">
<div class="progress-bar" role="progressbar"></div>
</div>
Jquery
$(document).ready(function(){
let percentValue = 0,
progressBar = $('.progress-bar');
timer = setInterval(startBar, 500);
$.ajax({
url: url,
type: "GET",
dataType: "json",
beforeSend: function(){
startBar();
},
success: function(){
clearInterval(timer);
}
}).done(function(data){
alert("success");
console.log(data);
}).fail(function(jqxhr, textStatus, error ){
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
function startBar(){
percentValue += 25;
progressBar.css("width", percentValue + "%").html(percentValue + "%");
}
});
我收到的结果大部分都会停在75%。我不会上传任何内容。它只是从服务器获取数据。如何让它停在100%?
最佳答案
- 该间隔将开始加载进度条,因此您不需要在 beforeSend 上调用它
- 成功后,如果百分比值小于 100,请将其设置为 75,以便它将在下一个时间间隔更新并结束
- startBar 方法检查百分比是否小于 100。如果是,它将更新并继续。否则,如果达到了100,就会终止间隔
$(document).ready(function(){
let percentValue = 0,
progressBar = $('.progress-bar');
timer = setInterval(startBar, 500);
$.ajax({
url: url,
type: "GET",
dataType: "json",
success: function(){
if (percentValue < 100) percentValue = 75;
}
}).done(function(data){
alert("success");
console.log(data);
}).fail(function(jqxhr, textStatus, error ){
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
function startBar(){
if (percentValue < 100) {
percentValue += 25;
progressBar.css("width", percentValue + "%").html(percentValue + "%");
} else {
clearInterval(timer);
}
}
});
关于javascript - 如何在ajax请求中将进度条停止在100%?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54222068/