首页 > 解决方案 > Bootbox dialog.modal('hide') 不隐藏模式

问题描述

我对 bootbox.js 模式有疑问。我想在执行 Ajax 并等待响应时使用 bootbox.dialog 暂停 UI。如果我dialog.modal('hide');在 bootbox.alert 中使用并确认(单击确定后它会隐藏 dialog.modal),一切都很好,但我不想每次都确认它。当我dialog.modal('hide');在 bootbox.alert 之外使用并确认它不会隐藏 dialog.modal... 问题出在哪里?工作代码(隐藏模式)在里面success,不工作在里面error

var dialog = bootbox.dialog({
            message: '<p class="text-center mb-0"><i class="fa fa-spin fa-cog"></i> Please wait while we do something...</p>',
            closeButton: false
        });
        var checkboxId = "#" + $(this).attr('id');
        var checked = $(this).is(":checked");
        if (checked) {
            $.ajax({
                url: url,
                type: "POST",
                data: { estimatedCostId: @Model.EstimatedCostID },
                success: function (data) {
                    if (!data.Success) 
                    {
                        bootbox.alert(data.ErrorMessage, function () {
                            dialog.modal('hide');
                        });
                        $(checkboxId).prop('checked', !checked);
                    }
                },
                error: function (request, status, error) {
                    dialog.modal('hide');
                    bootbox.alert("Błąd serwera");
                    $(checkboxId).prop('checked', !checked);
                }
            });
        }

标签: javascriptjqueryhtmlmodal-dialogbootbox

解决方案


最有可能的是,这是一个时间问题。如果您的 AJAX 调用“太快”,则在 bootbox.dialog 函数解析之前调用成功/失败回调。所以这:

dialog.modal('hide');

最终被一个未定义的对象调用。我在最近的一个项目中遇到了类似的问题,并通过将 AJAX 调用放入shown.bs.modal事件来解决它,如下所示:

var checkboxId = "#" + $(this).attr('id');
var checked = $(this).is(":checked");

var dialog = bootbox.dialog({
    message: '<p class="text-center mb-0"><i class="fa fa-spin fa-cog"></i> Please wait while we do something...</p>',
    closeButton: false
})
 // this is the change
.on('shown.bs.modal', function(){
    if (checked) {
        $.ajax({
            url: url,
            type: "POST",
            data: { estimatedCostId: @Model.EstimatedCostID },
            success: function (data) {
                if (!data.Success) 
                {
                    bootbox.alert(data.ErrorMessage, function () {
                        dialog.modal('hide');
                    });
                    $(checkboxId).prop('checked', !checked);
                }
            },
            error: function (request, status, error) {
                dialog.modal('hide');
                bootbox.alert("Błąd serwera");
                $(checkboxId).prop('checked', !checked);
            }
        });
    }
});

推荐阅读