欢迎访问宙启技术站
智能推送

bootstrap模态框远程示例代码分享

发布时间:2023-05-18 03:46:46

Bootstrap是一个流行的前端框架,其中Modal组件让我们轻松创建一个可自定义的模态框。而模态框除了展示静态信息外,更常用的场景是加载远程的数据。在这篇文章中,我将分享如何使用Bootstrap的Modal组件展示远程数据,并提供了示例代码。

首先,我们需要准备一个触发模态框的按钮和一个空的Modal容器。代码如下:

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">打开模态框</button>

<div class="modal fade" id="myModal">
  <div class="modal-dialog">
    <div class="modal-content">
    </div>
  </div>
</div>

这个按钮带有data-toggle="modal"data-target="#myModal"属性,告诉Bootstrap这个按钮要触发#myModal模态框。Modal容器包含一个.modal-dialog和一个.modal-content,我们将在这个.modal-content容器中展示远程数据。

接下来,我们需要使用jQuery在模态框打开时向服务器请求远程数据并将其展示在模态框中。代码如下:

$('#myModal').on('shown.bs.modal', function () {
  var modal = $(this)

  $.ajax({
    url: '/path/to/data',
    success: function (data) {
      modal.find('.modal-content').html(data)
    }
  })
})

这段代码定义了当模态框打开时,向服务器发起一个异步请求,请求的地址是/path/to/data。在请求成功时,我们使用modal.find('.modal-content')来找到.modal-content容器,并用html()方法替换它的内容为我们得到的数据。

最后,我们需要确保模态框关闭时清空内容,以免下次打开时内容被重复展示。代码如下:

$('#myModal').on('hidden.bs.modal', function () {
  $(this).find('.modal-content').empty()
})

这段代码定义了当模态框关闭时,清空.modal-content容器的内容。

最终的HTML代码如下:

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">打开模态框</button>

<div class="modal fade" id="myModal">
  <div class="modal-dialog">
    <div class="modal-content">
    </div>
  </div>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js"></script>
<script>
  $('#myModal').on('shown.bs.modal', function () {
    var modal = $(this)

    $.ajax({
      url: '/path/to/data',
      success: function (data) {
        modal.find('.modal-content').html(data)
      }
    })
  })

  $('#myModal').on('hidden.bs.modal', function () {
    $(this).find('.modal-content').empty()
  })
</script>

这就是一个简单的演示如何使用Bootstrap的模态框展示远程数据的例子。我们可以将其中的/path/to/data替换为我们需要请求数据的地址,就可以在模态框中展示远程数据了。