Why neither data-remote
or href
work on remote sites like youtube
Twitter bootstrap's modal uses AJAX to load remote content via data-remote
/href
. AJAX is constrained by the same origin policy so accessing a site with a different origin, like youtube, will produce this error:
No 'Access-Control-Allow-Origin' header is present on the requested resource
So neither data-remote
or href
will do what you want.
JSON:
If you were getting json data then you could potentially use JSONP. But since you need html, not json, from sites like youtube we need another approach:
Solution using <iFrame>
An <iframe>
will work for youtube and many other remote sites (even this solition doesn't work for all sites as some, like Facebook, explicitly block iframes by setting X-Frame-Options' to 'DENY') .
One way to use an iframe for dynamic content is to:
1) add an empty iframe inside your modal's body:
<div class="modal-body">
<iframe frameborder="0"></iframe>
</div>
2) add some jquery that is triggered when the modal dialog button is clicked. The following code expects a link destination in a data-src
attribute and for the button to have a class modalButton
. And optionally you can specify data-width
and data-height
- otherwise they default to 400 and 300 respectively (of course you can easily change those).
The attributes are then set on the <iframe>
which causes the iframe to load the specified page.
$('a.modalButton').on('click', function(e) {
var src = $(this).attr('data-src');
var height = $(this).attr('data-height') || 300;
var width = $(this).attr('data-width') || 400;
$("#myModal iframe").attr({'src':src,
'height': height,
'width': width});
});
3) add the class and attributes to the modal dialog's anchor tag:
<a class="modalButton" data-toggle="modal" data-src="http://www.youtube.com/embed/Oc8sWN_jNF4?rel=0&wmode=transparent&fs=0" data-height=320 data-width=450 data-target="#myModal">Click me</a>
Demo Fiddle using youtube
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…