繁体   English   中英

如何在 AJAX 成功后关闭模式 window

[英]How do I close a modal window after AJAX success

我有一个打开模态的按钮,但我通过单击背景或 ESC 键阻止了模态关闭。

我的按钮看起来像这样:

<button data-toggle="modal" data-target="#CompanyProfile"data-backdrop="static" data-keyboard="false">Click </button>

如何在使用 jQuery 成功$.ajax后关闭此模式?

我做了一些测试 - 模态已关闭但背景被锁定,在刷新页面之前我无法做任何事情

要关闭bootstrap模态,您可以将“hide”作为选项传递给模态方法,如下所示。

$('#CompanyProfile').modal('hide');

在ajax成功中使用此代码。

小提琴演示

添加此解决方案,因为似乎没有列出通用方法。

如果您希望在成功时关闭任何模态,但不希望将每个$ .ajax调用手工制作到服务器,则可以使用以下命令:

$('.modal form').on('submit', function(event) {
    event.preventDefault();
    $.ajax({
        url: $(this).attr('action'),
        type: 'POST',
        data: $(this).serializeObject(),
        contentType: 'application/json',
        beforeSend: function(xhr){xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")},
        success: function(data) {
            console.log(data.success);
            if(data.success===1) {
                // loop through all modal's and call the Bootstrap
                // modal jQuery extension's 'hide' method
                $('.modal').each(function(){
                    $(this).modal('hide');
                });
                console.log('success');
            } else {
                console.log('failure');
            }
        }
    });
});

$(this).serializeObject() ,如果您希望使用上面的代码作为复制/粘贴,您将需要以下内容来获取表单数据并将其转换为JSON以发布到服务器,或将$(this).serializeObject()更改为$(this).serialize()

$.fn.serializeObject = function() {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    o = { request: o };
    return o;
};

参考: Bootstrap JS Modal

你可以尝试类似的东西

 $( document ).ready(function() {               
        $(".btn").button().click(function(){         // button click

                $('#CompanyProfile').modal('show')   // Modal launch
                     $.ajax({
                              type: "POST",
                              url: "url",
                              data:{data:data},
                              cache: false,                         
                              success: function(data) { 
                                                  $('.text').html(data); 
                                                 }
                   })                          
         });   
  });

确保模态仅启动一次

你可以试试下面的东西。 未经测试但你会得到这个想法。

$.ajax({
  url: 'yourscript.php',
  data: $('form#yourForm').serialize(),
  type: 'post'
}).done(function(response) { 
  // trigger modal closing here since ajax is complete.
});

我定义我的模态:

  <div class="modal fade" aria-hidden="true" role="dialog" id="modal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button id="btnCloseModal" hidden type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <strong>Waiting</strong>
            </div>
            <div class="modal-content">
                <div>
                    Please don't close your tab!
                </div>
                <div class="d-flex justify-content-center">
                    <div class="spinner-border" role="status">
                        <span class="sr-only">Loading...</span>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <strong>Loading...</strong>
            </div>
        </div>
    </div>
</div>

然后我使用create function:

var StopLoadingAnimation = function () {
$('#modal').on('show.bs.modal', function (e) {
    console.log("trigger show");
    $("#btnCloseModal").trigger("click");
});
$('#modal').on('shown.bs.modal', function (e) {
    console.log("trigger");
    $("#btnCloseModal").trigger("click");
});
$('#modal').on('hidden.bs.modal', function (e) {
    console.log("event");
    $(e.currentTarget).off('shown');
    $(e.currentTarget).off('show');
});
$("#btnCloseModal").trigger("click");

}

我的想法是在ajax成功之后将调用函数StopLoadingAnimation将触发事件点击元素btnCloseModal(就像你关闭模式时点击按钮btnCloseModal)

使用$('#YourModalId').modal('toggle'); 如果您的目标是另一个模态内部(顶部)的模态。

在模态框内创建一个按钮,如下所示:

<button type="button" class="close" id="closemodal" data-dismiss="modal" aria-label="Close">

然后,在您的 ajax 中:

$.ajax
              ({
                  type: "POST",
                  url: "yourcode.php",
                  cache: false,
                  data: dataString,
                success: function(html)
                    {
                      $('#closemodal').click ();
                    }

希望这可以帮助!

使用设置超时

setTimeout(function () {
  $('#CompanyProfile').modal('hide');
}, 1000);
success :function(){
              console.log("success");
              $('#contact_modal').html("<img src='img/bg/success.gif'>").delay(3000).fadeOut(450);
              $('body').removeClass('modal-open');
              $('.modal-backdrop.show').css('opacity','0');
              $('.modal-backdrop').css('z-index','-1')
          }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM