PHP下ajax跨域的解決方案之window.name實(shí)例分析
本文實(shí)例講述了PHP下ajax跨域的解決方案之window.name。分享給大家供大家參考,具體如下:
原理核心:window對(duì)象的name屬性是一個(gè)很特別的屬性,當(dāng)該window的location變化,然后重新加載,它的name屬性可以依然保持不變。
依此原理,我們可以在頁(yè)面A中用iframe加載其他域的頁(yè)面B,而頁(yè)面B中用JavaScript把需要傳遞的數(shù)據(jù)賦值給 window.name,頁(yè)面A的iframe加載完成之后,頁(yè)面A修改iframe的地址,將其變成同域的一個(gè)地址,然后就可以讀出window.name的值了。
例:有兩個(gè)網(wǎng)站www.a.com和www.b.com,我們要在www.a.com/a.html下獲取www.b.com/data.html數(shù)據(jù)。
我們需要三個(gè)文件:
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 src='http://www.aoyou183.cn/bcjs/7849.html'></iframe> <!-- 顯示獲取到的數(shù)據(jù) --><div id='data'></div> <script type='text/javascript' src='http://www.aoyou183.cn/bcjs/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相關(guān)內(nèi)容可查看本站專題:《PHP+ajax技巧與應(yīng)用小結(jié)》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門教程》及《php常見數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
相關(guān)文章:
1. SpringBoot+SpringCache實(shí)現(xiàn)兩級(jí)緩存(Redis+Caffeine)2. Kotlin + Flow 實(shí)現(xiàn)Android 應(yīng)用初始化任務(wù)啟動(dòng)庫(kù)3. ASP.NET泛型三之使用協(xié)變和逆變實(shí)現(xiàn)類型轉(zhuǎn)換4. jsp文件下載功能實(shí)現(xiàn)代碼5. AJAX實(shí)現(xiàn)省市縣三級(jí)聯(lián)動(dòng)效果6. 快速解決ajax返回值給外部函數(shù)的問題7. ASP.NET MVC視圖頁(yè)使用jQuery傳遞異步數(shù)據(jù)的幾種方式詳解8. 每日六道java新手入門面試題,通往自由的道路--多線程9. 在JSP中使用formatNumber控制要顯示的小數(shù)位數(shù)方法10. 每日六道java新手入門面試題,通往自由的道路
