在jquery ajax帖子开始花费太长时间之后是否有可能只显示某种进展,但是如果相当即时的话,不要再显示它?我有以下代码使用setTimeout来延迟显示我的进度指示器(它基本上是我启用的twitter引导模式,并且它中有一个进度指示器gif),但是当我调试并放置一个brek时它似乎不起作用指向我的服务器端代码,然后,在我的客户端setTimeout中,它应该关闭,但是在我的服务器返回响应之前永远不会调用setTimeout(所以如果花费太长时间我就不会获得进度条)。当我不使用setTimeout来延迟它时(基本上不会延迟),或者如果我做了这么短的延迟,进度指示器几乎瞬间显示,但是没有1.5秒的延迟,它就可以正常工作。
这是我的javascript:
var progressModalRunning = false;
var needModalProgress = true;
// document.ready events/functions to call
$(function () {
$("form").on("submit", function (event) {
event.preventDefault();
var form = $(this);
// We check if jQuery.validator exists on the form
if (!form.valid || form.valid()) {
toggleModalProgressAndButtons(form, true);
$.post(form.attr('action'), form.serializeArray())
.done(function (json) {
json = json || {};
// In case of success, we redirect to the provided URL or the same page.
if (json.success) {
location = json.redirect || location.href;
} else if (json.errors) {
displayErrors(form, json.errors);
toggleModalProgressAndButtons(form, false);
}
})
.error(function () {
displayErrors(form, ['An unknown error happened.']);
toggleModalProgressAndButtons(form, false);
});
}
});
});
// show/hide modal progress indicator and disable/enable modal buttons
var toggleModalProgressAndButtons = function (form, toggle) {
if (toggle) {
showProgress();
} else {
hideProgress();
}
}
// display validation errors
var displayErrors = function (form, errors) {
needModalProgress = false;
var errorSummary = getValidationSummaryErrors(form)
.removeClass('validation-summary-valid')
.addClass('validation-summary-errors');
var items = $.map(errors, function (error) {
return '<li>' + error + '</li>';
}).join('');
var ul = errorSummary
.find('ul')
.empty()
.append(items);
};
// Show a progress indicator in it's own modal
var showProgress = function () {
// we will delay it by 1.5 seconds - don't want to bother showing if the response is that fast,
// because it makes the screen to appear to flicker since backdrop for modal is darker
setTimeout(function () {
if (needModalProgress) {
progressModalRunning = true;
$('#progress').modal({ keyboard: false, backdrop: 'static' });
}
}, 1500);
}
// hide the progress indicator
var hideProgress = function () {
if (progressModalRunning) {
progressModalRunning = false;
needModalProgress = true;
$('#progress').modal('hide');
}
}