js 跨域的几种方法
http://www.cnblogs.com/2050/p/3191744.html
js 同源策略:js 只能与同一域中的页面进行通讯
同源:相同协议(http/https)、相同域名、相同端口
1.jsonp 跨域
页面代码
<script>
function doSomething(json){
alert(json)
}
</script>
<script src='http://example.com/a.php?callback=doSomething'></script>
php代码
<?php
$callback = $_GET['callback'];
$data = array('a','b','c')'
echo $callback.'('.json_encode($data).')';
?>
最终页面输出 a ,b ,c
2.window.name 跨域
页面a.html
<script>
windw.name = '我的a.html的数据';
setTimeout(function(){
window.location = 'b.html';
},3000);
</script>
页面b.html
<script>
alert(window.name)
</script>
3.window.postMessage(message,targetOrigin)
html5特性,该方法的第一个参数message为要发送的消息,类型只能为字符串;第二个参数targetOrigin用来限定接收消息的那个window对象所在的域,如果不想限定域,可以使用通配符 * 。
a.html
<iframe id="myIframe" src="test.html" frameborder="0" onload="myload()"></iframe>
<script>
function myload(){
let f = document.getElementById('myIframe');
let win = f.contentWindow;
win.postMessage("我是index.html的数据","*");
}
</script>
b.html
<div id='div1'></div>
<script>
let d = document.getElementById('div1');
window.onmessage = function(e){
e = e || event;
d.innerHTML = e.data;
}
</script>

浙公网安备 33010602011771号