PHP ajax跨子域的解決方案之document.domain+iframe實(shí)例分析
本文實(shí)例講述了PHP ajax跨子域的解決方案之document.domain+iframe。分享給大家供大家參考,具體如下:
對(duì)于主域相同,子域不同,我們可以設(shè)置相同的document.domain來(lái)欺騙瀏覽器,達(dá)到跨子域的效果。
例如:我們有兩個(gè)域名:www.a.com 和 img.a.com
在www.a.com下有a.html
在img.a.com下有img.json和img.html這兩個(gè)文件。
img.json就是一些我們要獲取的數(shù)據(jù):
[ { 'name' : 'img1', 'url' : 'http://img.a.com/img1.jpg' }, { 'name' : 'img2', 'url' : 'http://img.a.com/img2.jpg' }]
img.html就是我們iframe要引用的:
<!DOCTYPE html><html><head> <meta charset='UTF-8'> <title>Insert title here</title></head><body><script src='http://www.hdgsjgj.cn/bcjs/jquery.js'></script><script type='text/javascript'> document.domain = 'a.com'; var p = parent.window.$; p('#sub').text('我是子頁(yè)面添加的');</script></body></html>
a.html就是要通過(guò)跨子域獲取數(shù)據(jù)的頁(yè)面:
<!DOCTYPE html><html><head> <meta charset='UTF-8'> <title>Insert title here</title></head><body><!-- 通過(guò)跨域獲取數(shù)據(jù),并添加到ul中 --><ul id='data'></ul><!-- 子頁(yè)面通過(guò)parent.window來(lái)訪問(wèn)父頁(yè)面 --><div id='sub'></div><!-- 通過(guò)iframe引用img.a.com下的img.html --><iframe src='http://img.a.com/img.html'></iframe><script src='http://www.hdgsjgj.cn/bcjs/jquery.js'></script><script type='text/javascript'>document.domain = 'a.com';$('#iframe').bind('load', function() { //獲取子頁(yè)面的jquery對(duì)象 iframe = document.getElementById('iframe').contentWindow.$; iframe.getJSON('http://img.a.com/img.json', function(data) { var con = ''; //注意這里的$對(duì)象是www.a.com上的 $.each(data, function(i, v) { con += '<li>' + v.name + ':' + v.url + '</li>'; }); $('#data').html(con); });});</script></body></html>
a.html中我們通過(guò)contentWindow.$來(lái)獲取子頁(yè)面的jquery對(duì)象,然后通過(guò)getJSON獲取數(shù)據(jù),并通過(guò)www.a.com上的$對(duì)象把數(shù)據(jù)寫(xiě)入到ul中。
在子頁(yè)面img.html中我們通過(guò)parent.window來(lái)訪問(wèn)父頁(yè)面的$對(duì)象,并操作元素添加數(shù)據(jù)。
更多關(guān)于PHP相關(guān)內(nèi)容可查看本站專(zhuān)題:《PHP+ajax技巧與應(yīng)用小結(jié)》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門(mén)教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
相關(guān)文章:
1. 使用Hangfire+.NET 6實(shí)現(xiàn)定時(shí)任務(wù)管理(推薦)2. Xml簡(jiǎn)介_(kāi)動(dòng)力節(jié)點(diǎn)Java學(xué)院整理3. 如何在jsp界面中插入圖片4. jsp實(shí)現(xiàn)登錄驗(yàn)證的過(guò)濾器5. phpstudy apache開(kāi)啟ssi使用詳解6. xml中的空格之完全解說(shuō)7. JSP之表單提交get和post的區(qū)別詳解及實(shí)例8. jsp文件下載功能實(shí)現(xiàn)代碼9. 詳解瀏覽器的緩存機(jī)制10. vue3+ts+elementPLus實(shí)現(xiàn)v-preview指令
