我有以下代码,当我点击按钮时执行。
当用户点击按钮时,我需要在浏览器中显示进度条/等待图像5秒钟。如何设置超时以及当用户单击按钮时如何在页面中显示进度条/等待页面图像
$("#btnSubmit").click(function(){
var formData = $("form").serialize();
$.ajax({
url: 'cgi-bin/config',
type: 'POST',
data: formData, // An object with the key 'submit' and value 'true;
success: function (result) {
console.log(result);
},
failure: function () {
alert("Ajax request failed!!!");
},error: function () {
alert("Ajax request failed to update data!!!");
}
});
});
答案 0 :(得分:0)
使用 beforeSend 和完成
$("#btnSubmit").click(function(){
var formData = $("form").serialize();
$.ajax({
url: 'cgi-bin/config',
type: 'POST',
data: formData, // An object with the key 'submit' and value 'true;
success: function (result) {
console.log(result);
},
failure: function () {
alert("Ajax request failed!!!");
},error: function () {
alert("Ajax request failed to update data!!!");
},
beforeSend: function(){
$('.progress').show();
},
complete: function(){
$('.progress').hide();
}
});
});
<强> HTML 强>
<div class="progress" style="display:none;"><img src="loading.gif" />Loading...</div>
答案 1 :(得分:0)
$("#btnSubmit").click(function(){
var startTime = Date.now(),
// finish function is called at the end - when request is completed and at least 5s passed
// result will be null on error or whatever was received by success callback
finish = function (result) {
if (result === null) {
// probably error, handle it..
} else {
// handle result
}
$('#progress').hide();
},
checkDone = function (result) {
var r = Date.now() - startTime; // time taken by request
if (r < 5000) { // if less than 5s then set timeout for remaining time
setTimeout(function () {
finish(result);
}, 5000 - r);
} else { // if there was already 5s finish immediately
finish(result);
}
},
formData = $("form").serialize();
$('#progress').show();
$.ajax({
url: 'cgi-bin/config',
type: 'POST',
data: formData, // An object with the key 'submit' and value 'true;
success: function (result) {
console.log(result);
checkDone(result);
},
failure: function () {
alert("Ajax request failed!!!");
checkDone(null);
},
error: function () {
alert("Ajax request failed to update data!!!");
checkDone(null);
}
});
});
进度div示例(刚放入正文):
<div id="progress" style="display:none;position:absolute;z-index:99999;top:0;left:0;width:100%;height:100%;opcity:0.7;background:url('/img/progress.gif') 50% 50% no-repeate #000"></div>