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

Thi*_*zar 71 ajax modal-dialog twitter-bootstrap twitter-bootstrap-3

正如你在这里看到的,我有一个启动模态的按钮.为按钮设置一个href url这个url会被Bootstrap 3自动加载到modal中.事实是这个页面被加载到模态根目录中(如用于模态使用bootstrap 3文档中所述).我想把它加载到模态体中.

有没有办法通过属性(而不是javascript)来做到这一点?或者最自动的方法是什么?

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

mar*_*out 88

这实际上非常简单,只需添加一点点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"));
});
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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

  • 你对错误的答案发表了评论吗?这个答案正是如此.;) (15认同)
  • 感谢您注意到这一点.官方文档在这里不是很清楚 - 我现在通过`data-remote ="false"`专门禁用了原始加载,并添加了一个JSfiddle.在Bootstrap 4中,不再需要这个. (5认同)
  • 在最新的Bootrat中,`load`函数已被删除并在Boostrap文档中说明:**此选项自v3.3.0起已弃用,将在v4中删除.我们建议使用客户端模板或数据绑定框架,或者自己调用jQuery.load.**希望看到更新版本 (4认同)

ale*_*oni 34

检查这个SO答案.

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

您可以从bootstrap 源代码中检查,load函数绑定到根元素.

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


小智 15

我想你正在寻找这个自定义功能.它采用数据切换属性并动态创建必要的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);
              }
            );
Run Code Online (Sandbox Code Playgroud)

最后,在远程内容中,您需要将整个结构运行起来.

<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 -->
Run Code Online (Sandbox Code Playgroud)


Zim*_*Zim 10

如果您需要使用来自不同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);
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

Bootstrap 3 Demo
Bootstrap 4演示


Sam*_*nto 5

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

来自github的 Ex :

  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');
    
    Run Code Online (Sandbox Code Playgroud)

$(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
});
Run Code Online (Sandbox Code Playgroud)
.fa{
  cursor:pointer;
 }
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)