首页 > 解决方案 > 提交表单和 API 调用竞争后,Bootstrap Spinner 不会停止

问题描述

我正在使用引导程序,并且正在尝试在提交表单时设置微调器。我可以在提交表单时让微调器按钮旋转,但是在提交后它只会继续旋转。我已经看了一遍,但似乎无法弄清楚一旦 API 调用完成后如何让它停止。我如何在提交表单时让它旋转,一旦 API 调用完成就停止并在 API 调用完成后再次返回可用按钮?

微调器不会停止

html代码

<form id="form_id" name="form_id" class="form_id" method="POST" >
    <div class="input-group-append">
        <button type="submit" id="btnFetch" class="btn btn-primary mb-2">Submit</button>
    </div>
</form>

JS代码

$(document).ready(function() {
    $("#btnFetch").click(function() {
        $(this).prop("disabled", true);
        $(this).html(
            `<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>Loading...`
        );
    });
});

阿贾克斯调用

$(document).ready(function() {
    $('.form_class1').on('submit', function(event) {
        $.ajax({
            data : {
                some_id: $('#some_id').val(),
            },
            type : 'POST',
            url : '/ajax_request_url1'

        })
        .done(function(data) {

            if (data.error) {

            }
            else {
                // Do Processing here....
            }

        });

        event.preventDefault();
        event.stopImmediatePropagation();

    });

});

标签: javascriptjquerybootstrap-4spinner

解决方案


您可能会考虑重新组织一些事情以简化正在发生的事情。

  1. 创建单独的函数来处理微调器状态。
function startSpinner() {
    // your code to make the spinner start
    $("#btnFetch").prop("disabled", true);
    $("#btnFetch").html(
        `<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>Loading...`
    );
}

function stopSpinner() {
    // you code to make the spinner stop
    // (i.e., return the button to its original state)
    $("#btnFetch").prop("disabled", false);
    $("#btnFetch").html('Submit');
}
  1. 在提交过程中的适当时间调用您的微调器函数。
$(document).ready(function() {
    $('.form_class1').on('submit', function(event) {

        // initiate spinner
        startSpinner();

        $.ajax({
            data : {
                some_id: $('#some_id').val(),
            },
            type : 'POST',
            url : '/ajax_request_url1'
        })
        .done(function(data) {
            // ...
        })
        .always(function(dataOrjqXHR, textStatus, jqXHRorErrorThrown) {           
            // do when complete, even on error            
            // stop the spinner
            stopSpinner();
        });

        // should these be at the top?
        event.preventDefault();
        event.stopImmediatePropagation();

    });

});

推荐阅读