有a.ceshi.com經過iframe加載b.ceshi.com下的內容,經過對兩個子域下的頁面同時設置document.domian設置爲相同的主域名可實現跨域讀取數據:javascript
a.ceshi.com頁面html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>ceshi1</title> </head> <body> 我是1 <div id="box1"></div> <script type="text/javascript"> //設置主域 document.domain = 'ceshi.com'; var iframe = document.createElement("iframe"); iframe.style.display = 'none'; //拉取b.ceshi.com內容 iframe.src = "http://b.ceshi.com"; document.body.appendChild(iframe); //判斷是否加載完成 //iframe取值方法可根據name或者id但各個瀏覽器均有不一樣爲了兼容IE/FF/Chrome方法以下 //統一使用iframe的id進行取值 document.getElementById('iframe_id').contentWindow.document.body.innerHTML if (iframe.attachEvent){ //ie iframe.attachEvent("onload", function(){ alert("Local iframe is now loaded."); alert(iframe.contentWindow.document.body.innerHTML) document.getElementById('box1').innerHTML = iframe.contentWindow.document.body.innerHTML; }); } else { iframe.onload = function(){ //chrome/ff alert("Local iframe is now loaded."); alert(iframe.contentWindow.document.body.innerHTML) document.getElementById('box1').innerHTML = iframe.contentWindow.document.body.innerHTML; }; } </script> </body> </html>
b.ceshi.com頁面java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>ceshi2</title> </head> <body> 我是2 <script type="text/javascript"> //設置主域 document.domain = 'ceshi.com'; </script> </body> </html>
這樣就能夠從a.ceshi.com讀取到b.ceshi.com的內容了。chrome
至於經過iframe跨不一樣主域名的,待續。。。跨域