javascript - jQuery AJAX 触发太快

标签 javascript jquery ajax asynchronous

我有一个包装在函数中的相对简单的 jQuery AJAX 调用,我正在测试我的错误功能。我面临的问题是 AJAX 调用发生得太快了!它导致我的“H6”和“.loading”元素开始重复。我需要的行为是删除元素,然后调用 ajax。

function getAvailability(form) {
    var str = $(form).serialize(),
    warning = $('#content h6');

    if ( warning.length > 0 ) {
        $(warning).remove();
        $('<div class="loading">Loading&hellip;</div>').insertAfter(form);
    }
    else
    {
        $('<div class="loading">Loading&hellip;</div>').insertAfter(form);
    }

    $.ajax({
        type: "POST",
        url: "someFile",
        data: str,

        success: function(calendar) {
            $('.loading').fadeOut(function() {
                $(this).remove();
                $(calendar).insertAfter(form).hide().fadeIn();
            });
        },
        error: function() {
            $('.loading').fadeOut(function() {
                $('<h6>Unfortunately there has been an error and we can not show you the availability at this time.</h6>').insertAfter(form);
            });
        }
    });

    return false;
}

我喜欢这样排序 -> 从页面中删除“警告”,添加 .loading。然后触发AJAX。然后淡出 .loading,根据成功添加和淡入警告/日历。


我已经修改了我的原始代码,并且我得到了按预期运行的函数,主要是因为我在 ajax 过程中禁用了提交按钮。

function getAvailability(form) {
    var str = $(form).serialize(),
    btn = $('#property_availability');

    // Disable submit btn, remove original 'warning', add loading spinner
    btn.attr("disabled", "true");
    $('.warning').remove();
    $('<div class="loading">Loading&hellip;</div>').insertAfter(form);

    $.ajax({
        type: "POST",
        url: "public/ajax/returnAvailability1.php",
        data: str,

        success: function(calendar) {
            $('.loading').fadeOut(function() {
                $(this).remove();
                $(calendar).insertAfter(form).hide().fadeIn();
            });
        },
        error: function() {
            $('.loading').fadeOut(function() {
                $(this).remove();
                $('<h6 class="warning">Unfortunately there has been an error and we can not show you the availability at this time.</h6>').insertAfter(form);
                btn.removeAttr("disabled");
            });
        }
    });

    return false;
}

我认为由于 fadeOut() 函数造成的时间延迟,原始序列没有按预期工作。

最佳答案

与其添加和删除 warning,不如显示/隐藏利用 ajaxStart 和 ajaxStop?

warning.ajaxStart(function() {
    $(this).show();
}).ajaxStop(function() {
    $(this).fadeOut();
});

关于javascript - jQuery AJAX 触发太快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15837394/

相关文章:

javascript - 购物车中的 WooCommerce 加号/减号按钮间歇性显示

javascript - 如何使用 jquery 将下一个和上一个按钮添加到灯箱

javascript - 哪些 Javascript IDE 可以显示 Three.js 的代码提示?

使用图像提交 JavaScript 表单不起作用

javascript - 缩放后获取 Canvas 上鼠标的相对位置

javascript - 减少大型 javascript 操作对客户端的明显滞后的方法

jquery - 如何优化我的 JavaScript 代码?

javascript - 长 JavaScript 函数末尾的 CSS 元素更新

javascript - AJAX 表单提交后永无止境的 "Connecting"消息

javascript - 有没有更好的方法可以测量从 Ajax 调用返回数据所需的总时间?