html5 提供了跨文档消息传输(Cross Document Messaging),可利用其进行跨域请求
如:www.a.com/a.html 请求 www.b.com/b.html
1. 在a.html中内嵌iframe,通过iframe向b.html 发送message, 并准备接收消息
<iframe src="http://b.com/b.html"></iframe> <script type="text/javascript"> window.onmessage = function( event ) { alert( event.data ); } var iframe = document.getElementsByTagName('iframe')[0]; iframe.onload = function() { iframe.contentWindow.postMessage( null, 'http://b.com/b.html' ); } </script>
2. b.html中接收到message事件时向不源传送数据
window.onmessage = function( event ) { var data = { "name":"zhangsan" }; evt.source.postMessage( data, event.origin ); }
ie8以下不支持
评论