標籤:images class 屬性 str logs ons window 回呼函數 stat
只要協議、網域名稱、連接埠有任何一個不同,都被當作是不同的域。
也就是“http://www.baidu.com”這個URL首部,必須完全一樣才能互相通訊。
一、通過jsonp跨域
原理:不同的域可以傳輸JS檔案
伺服器的data.php:
<?php$callback=$_GET[‘callback‘];//得到的回呼函數名$data=array(‘a‘,‘b‘,‘c‘);//需要返回的資料echo $callback.‘(‘.json_encode($data).‘)‘;//輸出?>
HTML:
<!DOCTYPE html><html><head> <meta charset="utf-8"> <title>跨域</title> </head><body><script> function dosomething(jsondata){ console.log(jsondata) }</script><script src=‘http://oa.daoyoudashi.com/shen/data.php?callback=dosomething‘></script></body></html>
或者用jquery:
<!DOCTYPE html><html><head> <meta charset="utf-8"> <title>跨域</title> <script src="http://cdn.static.runoob.com/libs/jquery/1.8.3/jquery.js"></script> </head><body><script>$.getJSON("http://oa.daoyoudashi.com/shen/data.php?callback=?", function(jsondata) { console.log(jsondata);});</script></body></html>
結果:
["a","b","c"]
2、通過修改document.domain來跨子域
伺服器中的a.html
<!DOCTYPE html><html><head> <meta charset="utf-8"> <title>a跨域</title></head><body><script>function onLoad(){ var iframe=document.getElementById(‘iframe‘); console.log(iframe); var win=iframe.contentWindow; console.log(win); var doc=win.document; console.log(doc); var name=win.name; console.log(name); //無法擷取window對象的name屬性}</script><iframe id="iframe" src="http://oa.daoyoudashi.com/shen/b.html" onload="onLoad()"></iframe></body></html>
伺服器中的b.html
<!DOCTYPE html><html><head> <meta charset="utf-8"> <title>b跨域</title> </head><body><div>內容</div></body></html>
結果:
JavaScript跨域