工作中遇到的js跨域問題總結
阿新 • • 發佈:2019-05-15
沒事 eid down window function fun class tle 需要
起因:之前在做一個項目的時候有這樣一個問題,127.0.0.1域名上的一個頁面A.html,需要訪問127.0.0.2域名上B.html頁面中的一個方法。這就涉及到JS跨域訪問了,通過查閱資料,得以解決,現總結一下。
具體問題:在A.html頁面有一個下載按鈕,當點擊下載的時候,要訪問B.html頁面的方法,然後下載資源,苦苦尋找,終得良方。
良方如下:
第一步 在A.html頁面裏面創建一個 iframe ,
//導出按鈕 $("#導出").click(function () { exec_iframe() }); //跨域訪問execB.html頁面 function exec_iframe() { if (typeof (exec_obj) == ‘undefined‘) { exec_obj = document.createElement(‘iframe‘); exec_obj.name = ‘tmp_frame‘; exec_obj.src = "http://127.0.0.2:8001"+‘/execB.html‘; exec_obj.style.display = ‘none‘; document.body.appendChild(exec_obj); } else { exec_obj.src = "http://127.0.0.2:8001"+‘/execB.html‘; } }
<iframe id="BpageId" name="myframe" src="http://127.0.0.2:8001/B.html" frameborder="0" scrolling="auto" style="width: 100%; height: 327px;"></iframe>
第二步 創建B.html, execB.html頁面,這兩個頁面都屬於127.0.0.2:8001域下的頁面,兩個頁面的內容如下
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title> exec iframe function </title> </head> <body> <script type="text/javascript"> parent.window.myframe.downFile(); // execute parent myframe fIframe function </script> </body> </html>
B.html
function downFile() { 下載 }
如此一來,便可解決,閑的沒事,寫寫博客!!!
工作中遇到的js跨域問題總結