PHP下ajax如何跨域的解決方案之window.name?針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
原理核心:window對象的name屬性是一個很特別的屬性,當(dāng)該window的location變化,然后重新加載,它的name屬性可以依然保持不變。
依此原理,我們可以在頁面A中用iframe加載其他域的頁面B,而頁面B中用JavaScript把需要傳遞的數(shù)據(jù)賦值給 window.name,頁面A的iframe加載完成之后,頁面A修改iframe的地址,將其變成同域的一個地址,然后就可以讀出window.name的值了。
例:有兩個網(wǎng)站www.a.com和www.b.com,我們要在www.a.com/a.html下獲取www.b.com/data.html數(shù)據(jù)。
我們需要三個文件:
www.a.com 下的 a.html 獲取數(shù)據(jù)并顯示
www.b.com 下的data.html 提供數(shù)據(jù)
www.a.com 下的proxy.html 代理文件,與a.html同一域下,一般為空html文件。
www.b.com下的data.html如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <script type="text/javascript"> //添加需要傳遞的數(shù)據(jù),大小一般為2M,IE和firefox下可以大至32M左右 window.name = '[{"name":"test1"},{"name":"test2"}]'; </script> </body> </html>
www.a.com下的proxy.html如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <!-- 空的html文件 --> </body> </html>
www.a.com下的a.html如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <!-- 用于引用www.b.com/data.html文件 --> <iframe id="iframe" src=""></iframe> <!-- 顯示獲取到的數(shù)據(jù) --> <p id="data"></p> <script type="text/javascript" src="./jquery.js"></script> <script type="text/javascript"> var ifr = document.getElementById("iframe"); ifr.src = "http://www.b.com/data.html"; if (ifr.attachEvent) { ifr.attachEvent("onload", loadfunc); } else { ifr.onload = loadfunc; } var state = 0; function loadfunc() { if(state == 0) { state = 1; ifr.contentWindow.location = "http://www.a.com/proxy.html"; } else { var data = ifr.contentWindow.name; $.each($.parseJSON(data), function(i, v) { $("#data").append(v.name); }); //銷毀iframe,保證安全 ifr.contentWindow.document.write(""); ifr.contentWindow.close(); document.body.removeChild(ifr); } } </script> </body> </html>
關(guān)于PHP下ajax如何跨域的解決方案之window.name問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)-成都網(wǎng)站建設(shè)公司行業(yè)資訊頻道了解更多相關(guān)知識。
本文題目:PHP下ajax如何跨域的解決方案之window.name-創(chuàng)新互聯(lián)
URL鏈接:http://www.rwnh.cn/article12/gesdc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供自適應(yīng)網(wǎng)站、網(wǎng)站設(shè)計、網(wǎng)站維護(hù)、定制開發(fā)、做網(wǎng)站、網(wǎng)站策劃
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容