同源策略阻止從一個域上加載的腳本獲取或操做另外一個域上的文檔屬性。也就是說,受到的請求的URL的域必須與當前Web頁面的域相同。存在如下任一狀況,即發生跨域:html
1. 基於iframenode
對於主域名(基礎域名)相同而子域名不一樣的狀況,也就是兩個頁面必須屬於同一個基礎域,使用贊成協議(例如http)和同一端口。能夠經過這種方法來解決。能夠在http://www.example.com/a.html和http://api.example.com/b.html兩個文件中分別添加document.domain = ‘example.com’,而後在a.html中建立一個iframe指向b.html,即a.html是父頁面,b.html是個子頁面。api
www.example.com上的a.html:跨域
<html> <head> <script> document.domain = "example.com"; var ifr = document.createElement('iframe'); ifr.src = 'http://api.example.com/b.html'; ifr.style.display = 'none'; document.body.appendChild(ifr); ifr.onload = function(){ var doc = ifr.contentDocument || ifr.contentWindow.document; // 在這裏操縱b.html alert(doc.getElementsByTagName("h1")[0].childNodes[0].nodeValue); }; </script> </head> <body> </body> </html>
api.example.com上的b.html瀏覽器
<html> <head> <script> document.domain = "example.com"; function a(){ alert("c"); } </script> </head> <body> </body> </html>
注意:安全
2. 動態建立script標籤網絡
script標籤能夠訪問任何域的資源,不受瀏覽器同源策略的限制,因此能夠經過在頁面動態建立script標籤的方法來實現跨域。app
var script = document.createElement('script'); script.src = "http://www.example.com/js/*.js"; document.body.appendChild(script);
這樣就加載到了其餘域的js文件,而後能夠在本頁面內調用加載的js文件中的函數。JSONP就是經過這個方式實現的,實現細節有些不一樣。dom
其餘跨域方法能夠參考如下兩篇文章:函數
http://www.cnblogs.com/rainman/archive/2011/02/20/1959325.html#m3