我正在尝试在ajax运行时添加进度条或微调器,但进度条和微调器只会与ajax的成功警报同时出现。
注意:我使用的是JSP,而ajax用于通过servlet更新数据库数据。进度条正在使用bootstrap。
$('#sync').click(function () {
var start = $('#startdate').val();
var end = $('#enddate').val();
if ((start !== "") && (end !== "")) {
var startDate = new Date(start);
var endDate = new Date(end);
$('#cover').show();
$.ajax({
type: "post",
url: "PRSync",
data: "start=" + startDate.yyyymmdd() +
"&end=" + endDate.yyyymmdd(),
async: false,
beforeSend: function () {
},
success: function (data) {
var arr = data.split('|');
if (arr[0] === "0") {
alert("Sync fail");
} else {
alert("Sync Succesfull. Total rows of " + arr[1] + " affected.");
}
},
error: function (jqXHR, textStatus, errorThrown, err4) { // if error occured
alert(jqXHR + " _ " + textStatus + " _ " + errorThrown + " _ " + err4);
},
complete: function () {
$('#cover').fadeOut(1000);
}
});
}
});
$(document).ajaxStart(function () {
// show loader on start
showbusy();
}).ajaxSuccess(function () {
// hide loader on success
hidebusy();
});
Date.prototype.yyyymmdd = function () {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth() + 1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + "-" + (mm[1] ? mm : "0" + mm[0]) + "-" + (dd[1] ? dd : "0" + dd[0]); // padding
};
var myApp;
myApp = myApp || (function () {
var pleaseWaitDiv = $('<div class="modal fade" style=top:40% id="pleaseWaitDialog" data-backdrop="false" data-keyboard="false"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h4 class="modal-title">Synchronizing is processing</h4></div><div class="modal-body"><div class="progress"><div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%"></div></div></div></div></div></div>');
return {
showPleaseWait: function () {
pleaseWaitDiv.modal();
},
hidePleaseWait: function () {
pleaseWaitDiv.modal('hide');
},
};
})();
function showbusy() {
myApp.showPleaseWait();
}
function hidebusy() {
myApp.hidePleaseWait();
}
答案 0 :(得分:2)
你试过这个:
$(document).bind("ajaxStart", function(){
showbusy(); })
.bind("ajaxStop", function(){
hidebusy();
});
显然,如果您的ajax调用处理速度非常快,那么您的功能可能会被触发并延迟发送,但是通过将事件绑定到$(document)
,您可以确保它们不是只触发一次。
如果仍然无法满足您的需求,我会将这些函数放在ajax调用中:
$.ajax({
beforeSend: showbusy(),
complete: hidebusy()
});
答案 1 :(得分:2)