【问题标题】:Twitter bootstrap modal external urls are not workingTwitter 引导模式外部 URL 不起作用
【发布时间】:2012-08-28 05:58:32
【问题描述】:

Twitter 引导模式不会在模式中加载外部 URL。

示例代码:jsFiddle

<a data-toggle="modal" class="btn" href="http://stackoverflow.com" data-target="#myModal">click me</a>
<div class="modal hide fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Modal header</h3>
  </div>
  <div class="modal-body">
  </div>
</div>

【问题讨论】:

    标签: twitter-bootstrap modal-dialog


    【解决方案1】:

    这不起作用,因为您违反了相同的origin policy restriction,它阻止您发送跨域 AJAX 请求,这正是 bootstrap 在这里使用的。所以一种可能性是将外部内容加载到&lt;iframe&gt;:

    $('a.btn').on('click', function(e) {
        e.preventDefault();
        var url = $(this).attr('href');
        $('.modal-body').html('<iframe width="100%" height="100%" frameborder="0" scrolling="no" allowtransparency="true" src="' + url + '"></iframe>');
    });​
    

    请注意,某些网站(例如 google、stackoverflow、facebook 等)无法加载到 iframe 中。他们将X-Frame-Options 响应HTTP 标头设置为SAMEORIGIN,并检查它们是否加载到iframe 中。

    您可以在这个小提琴中看到它的实际效果:http://jsfiddle.net/f2Fcd/

    【讨论】:

    • 感谢您的回复。我使用外部 url 来检查这个问题是 js fiddle。我想加载我的内部 asp.net mvc 视图以加载内部模型。这对我不起作用。出于示例目的,我使用 helloworld.html jsfiddle.net/kV8hB/3 谢谢 Naveen
    • 如果你想加载你的内部 ASP.NET MVC 视图,那么你不需要 iframe。只要确保网址正确。例如,如果您将href 中的网址直接放在浏览器地址栏中会发生什么?有效吗?
    【解决方案2】:

    试试这个:

    <script type="text/javascript" charset="utf-8">
    $(function() {
     $('*[data-modal]').click(function(e) {
     e.preventDefault();
     var href = $(e.target).attr('href');
      if (href.indexOf('#') == 0) {
       $(href).modal('show');
      } else {
        $.get(href, function(data) {
        $('<div class="modal">' + data + '</div>').modal('show').appendTo('body');
                            });
                        }
                    });
                });
            </script>
    

    【讨论】:

      【解决方案3】:

      这个 sn-p 有助于通过 Ajax 获取模态内容:

      $.get(href, function(response) {
           $("#myModal .modal-content").html(response);
      });
      

      请记住,获取的 HTML response 必须包含通常存在于“modal-content”元素中的 dom 元素:

       <div class="modal-header">HEADER</div>
       <div class="modal-body">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">Do It</button>
       </div>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多