1. 程式人生 > 實用技巧 >使用document.domain+iframe跨域例項

使用document.domain+iframe跨域例項

首先我們假設主頁面地址為:http://www.js8.in/mywork/crossdomain/index.html,我們要載入的內容是位於work.2fool.cn域名下的helloworld.txt。我們需要在主頁面中設定document.domain為2fool.cn,然後主頁面新增一個iframe,src為域名work.2fool.cn下的一個url,在iframe頁面中同樣設定document.domain為2fool.cn,同時iframe中需要新增Ajax的函式,例如引入jQuery.js。

 主頁index.html的主要程式碼如下:

<button onclick="crossDomain();"
>開始跨域</button> <div id="ajax"></div> <iframe src="http://work.2fool.cn/crossdomain/iframe.html" id="iframe" style="display:none;"> </iframe> <script type="text/javascript"> document.domain = '2fool.cn'; function crossDomain(){ var iframe=document.getElementById(
'iframe').contentWindow.$; iframe.get("http://work.2fool.cn/crossdomain/helloworld.txt",function(data){ document.getElementById("ajax").innerHTML=data; }); } </script>

轉載地址:https://www.cnblogs.com/shiyunfront/p/10407189.html