Bootstrap 3-如何通过AJAX在模态主体中加载内容?


76

如您在这里看到的,我有一个启动模态的按钮。设置按钮的href网址,该网址会由Bootstrap 3自动加载到模式中。事实是,此页面已加载到模式根中(如有关模式使用bootstrap 3文档中所述)。我想将其加载到模态主体中。

有没有一种方法可以通过属性(不是javascript)做到这一点?或最自动的方法是什么?

PS:我记得在Bootstrap 2中,内容已加载到正文中,而不是根目录中。

Answers:


35

检查这个答案

看起来唯一的方法是为您的ajax响应提供整个模式结构。

正如您可以从引导程序源代码中检查的那样,将load函数绑定到根元素。

如果您无法修改Ajax响应,则一个简单的解决方法是$(..).modal(..)在您的body元素上显式调用该插件,即使该插件可能会破坏根元素的show / hide功能。


95

实际上,这非常简单,只添加了一些JavaScript。链接的href用作ajax内容源。请注意,对于Bootstrap 3. *,我们设置data-remote="false"为禁用不推荐使用的Bootstrap加载功能

JavaScript:

// Fill modal with content from link href
$("#myModal").on("show.bs.modal", function(e) {
    var link = $(e.relatedTarget);
    $(this).find(".modal-body").load(link.attr("href"));
});

HTML(基于官方示例):

<!-- Link trigger modal -->
<a href="remoteContent.html" data-remote="false" data-toggle="modal" data-target="#myModal" class="btn btn-default">
    Launch Modal
</a>

<!-- Default bootstrap modal example -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

自己尝试:https//jsfiddle.net/ednon5d1/


5
在最新的Bootrat中,该load函数已被弃用,并在Boostrap文档中对此进行了说明:此选项自v3.3.0起不推荐使用,并将在v4中删除。我们建议改为使用客户端模板或数据绑定框架,或者自己调用jQuery.load。希望看到更新的版本
JasonDavis

16
您对错误答案有何评论?这个答案正是这样做的。;)
marcovtwout 2015年

1
这会在Bootstrap v3中触发2次ajax调用。一个用于原始Modal AJAX加载-一个用于您的show.bs.modal事件(在原始ajax调用之后触发)。
劳伦斯

6
感谢您注意到这一点。这里的官方文档不是很清楚-我现在专门禁用了原始加载data-remote="false"并添加了JSfiddle。在Bootstrap 4中,不再需要此功能。
marcovtwout 2015年

也有一种简单的方法来设置模式标题吗?首先想到的是再打电话给ajax,但这并不好...
Hokascha

16

我猜您正在搜索此自定义函数。它具有data-toggle属性,并动态创建必要的div来放置远程内容。只需将data-toggle =“ ajaxModal”放置在要通过AJAX加载的任何链接上。

JS部分:

$('[data-toggle="ajaxModal"]').on('click',
              function(e) {
                $('#ajaxModal').remove();
                e.preventDefault();
                var $this = $(this)
                  , $remote = $this.data('remote') || $this.attr('href')
                  , $modal = $('<div class="modal" id="ajaxModal"><div class="modal-body"></div></div>');
                $('body').append($modal);
                $modal.modal({backdrop: 'static', keyboard: false});
                $modal.load($remote);
              }
            );

最后,在远程内容中,您需要使整个结构起作用。

<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title"></h4>
        </div>
        <div class="modal-body">
        </div>
        <div class="modal-footer">
            <a href="#" class="btn btn-white" data-dismiss="modal">Close</a>
            <a href="#" class="btn btn-primary">Button</a>
            <a href="#" class="btn btn-primary">Another button...</a>
        </div>
    </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

这就是我现在正在做的方式,除了我有一个modal_create_head和modal_create_foot函数,然后我将介于两者之间的任何ajax返回。我认为这比在ajax框中加载html更快,因为您的.js文件将由客户端缓存并继续重复使用,不是吗?为什么人们加载.html而不是返回Json或Text或HTML中的所有html代码,而是更快地加载HTML?
特殊的人

13

如果您需要使用来自不同Ajax / API调用的内容来更新相同的模式,这是一个可行的解决方案。

$('.btn-action').click(function(){
    var url = $(this).data("url"); 
    $.ajax({
        url: url,
        dataType: 'json',
        success: function(res) {

            // get the ajax response data
            var data = res.body;

            // update modal content here
            // you may want to format data or 
            // update other modal elements here too
            $('.modal-body').text(data);

            // show modal
            $('#myModal').modal('show');

        },
        error:function(request, status, error) {
            console.log("ajax call went wrong:" + request.responseText);
        }
    });
});

Bootstrap 3演示
Bootstrap 4演示


不错,干净有效!也推荐。
新手'18

5

使用模态的一种简单方法是使用eModal

来自github的示例:

  1. 链接到eModal.js <script src="//rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>
  2. 使用eModal显示警报,ajax,提示或确认的模式

    // Display an alert modal with default title (Attention)
    eModal.ajax('your/url.html');
    

$(document).ready(function () {/* activate scroll spy menu */

    var iconPrefix = '.glyphicon-';


    $(iconPrefix + 'cloud').click(ajaxDemo);
    $(iconPrefix + 'comment').click(alertDemo);
    $(iconPrefix + 'ok').click(confirmDemo);
    $(iconPrefix + 'pencil').click(promptDemo);
    $(iconPrefix + 'screenshot').click(iframeDemo);
    ///////////////////* Implementation *///////////////////

    // Demos
    function ajaxDemo() {
        var title = 'Ajax modal';
        var params = {
            buttons: [
               { text: 'Close', close: true, style: 'danger' },
               { text: 'New content', close: false, style: 'success', click: ajaxDemo }
            ],
            size: eModal.size.lg,
            title: title,
            url: 'http://maispc.com/app/proxy.php?url=http://loripsum.net/api/' + Math.floor((Math.random() * 7) + 1) + '/short/ul/bq/prude/code/decorete'
        };

        return eModal
            .ajax(params)
            .then(function () { alert('Ajax Request complete!!!!', title) });
    }

    function alertDemo() {
        var title = 'Alert modal';
        return eModal
            .alert('You welcome! Want clean code ?', title)
            .then(function () { alert('Alert modal is visible.', title); });
    }

    function confirmDemo() {
        var title = 'Confirm modal callback feedback';
        return eModal
            .confirm('It is simple enough?', 'Confirm modal')
            .then(function (/* DOM */) { alert('Thank you for your OK pressed!', title); })
            .fail(function (/*null*/) { alert('Thank you for your Cancel pressed!', title) });
    }

    function iframeDemo() {
        var title = 'Insiders';
        return eModal
            .iframe('https://www.youtube.com/embed/VTkvN51OPfI', title)
            .then(function () { alert('iFrame loaded!!!!', title) });
    }

    function promptDemo() {
        var title = 'Prompt modal callback feedback';
        return eModal
            .prompt({ size: eModal.size.sm, message: 'What\'s your name?', title: title })
            .then(function (input) { alert({ message: 'Hi ' + input + '!', title: title, imgURI: 'https://avatars0.githubusercontent.com/u/4276775?v=3&s=89' }) })
            .fail(function (/**/) { alert('Why don\'t you tell me your name?', title); });
    }

    //#endregion
});
.fa{
  cursor:pointer;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>


<link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.5/united/bootstrap.min.css" rel="stylesheet" >
<link href="http//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">

<div class="row" itemprop="about">
	<div class="col-sm-1 text-center"></div>
	<div class="col-sm-2 text-center">
		<div class="row">
			<div class="col-sm-10 text-center">
				<h3>Ajax</h3>
				<p>You must get the message from a remote server? No problem!</p>
				<i class="glyphicon glyphicon-cloud fa-5x pointer" title="Try me!"></i>
			</div>
		</div>
	</div>
	<div class="col-sm-2 text-center">
		<div class="row">
			<div class="col-sm-10 text-center">
				<h3>Alert</h3>
				<p>Traditional alert box. Using only text or a lot of magic!?</p>
				<i class="glyphicon glyphicon-comment fa-5x pointer" title="Try me!"></i>
			</div>
		</div>
	</div>

	<div class="col-sm-2 text-center">
		<div class="row">
			<div class="col-sm-10 text-center">
				<h3>Confirm</h3>
				<p>Get an okay from user, has never been so simple and clean!</p>
				<i class="glyphicon glyphicon-ok fa-5x pointer" title="Try me!"></i>
			</div>
		</div>
	</div>
	<div class="col-sm-2 text-center">
		<div class="row">
			<div class="col-sm-10  text-center">
				<h3>Prompt</h3>
				<p>Do you have a question for the user? We take care of it...</p>
				<i class="glyphicon glyphicon-pencil fa-5x pointer" title="Try me!"></i>
			</div>
		</div>
	</div>
	<div class="col-sm-2 text-center">
		<div class="row">
			<div class="col-sm-10  text-center">
				<h3>iFrame</h3>
				<p>IFrames are hard to deal with it? We don't think so!</p>
				<i class="glyphicon glyphicon-screenshot fa-5x pointer" title="Try me!"></i>
			</div>
		</div>
	</div>
	<div class="col-sm-1 text-center"></div>
</div>


看起来很不错,但是完整的代码示例(也许usine jsfiddle.net)会更有趣。
Mike Castro Demaria 2015年

1
嗨,迈克,在后期版本中看一下...我在官方网站上添加了完整的演示
塞缪尔·平托

3

在当前页面上创建一个空的模式框,下面是ajax调用,您可以看到如何从另一个html页面获取结果中的内容。

 $.ajax({url: "registration.html", success: function(result){
            //alert("success"+result);
              $("#contentBody").html(result);
            $("#myModal").modal('show'); 

        }});

调用完成后,您将通过结果获得页面的内容,然后可以使用模态的内容ID插入代码。

您可以调用controller并获取页面内容,然后可以在模式中显示它。

下面是Bootstrap 3模式的示例,因为我们正在从registration.html页面加载内容...

index.html
------------------------------------------------
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script type="text/javascript">
function loadme(){
    //alert("loadig");

    $.ajax({url: "registration.html", success: function(result){
        //alert("success"+result);
          $("#contentBody").html(result);
        $("#myModal").modal('show'); 

    }});
}
</script>
</head>
<body>

<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" onclick="loadme()">Load me</button>


<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content" >
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body" id="contentBody">

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>

</body>
</html>

registration.html
-------------------- 
<!DOCTYPE html>
<html>
<style>
body {font-family: Arial, Helvetica, sans-serif;}

form {
    border: 3px solid #f1f1f1;
    font-family: Arial;
}

.container {
    padding: 20px;
    background-color: #f1f1f1;
    width: 560px;
}

input[type=text], input[type=submit] {
    width: 100%;
    padding: 12px;
    margin: 8px 0;
    display: inline-block;
    border: 1px solid #ccc;
    box-sizing: border-box;
}

input[type=checkbox] {
    margin-top: 16px;
}

input[type=submit] {
    background-color: #4CAF50;
    color: white;
    border: none;
}

input[type=submit]:hover {
    opacity: 0.8;
}
</style>
<body>

<h2>CSS Newsletter</h2>

<form action="/action_page.php">
  <div class="container">
    <h2>Subscribe to our Newsletter</h2>
    <p>Lorem ipsum text about why you should subscribe to our newsletter blabla. Lorem ipsum text about why you should subscribe to our newsletter blabla.</p>
  </div>

  <div class="container" style="background-color:white">
    <input type="text" placeholder="Name" name="name" required>
    <input type="text" placeholder="Email address" name="mail" required>
    <label>
      <input type="checkbox" checked="checked" name="subscribe"> Daily Newsletter
    </label>
  </div>

  <div class="container">
    <input type="submit" value="Subscribe">
  </div>
</form>

</body>
</html>

请不要使用代码格式的代码的解释-它们分开
nj2237
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.