使用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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM