1

是否有可能只在 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');
    }
}
4

0 回答 0