小編給大家分享一下PHP中如何解決ajax跨子域的問題,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
具體如下:
對于主域相同,子域不同,我們可以設(shè)置相同的document.domain來欺騙瀏覽器,達(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" : "/tupian/20230522/404.html }, { "name" : "img2", "url" : "/tupian/20230522/404.html } ]
img.html就是我們iframe要引用的:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <script src="./jquery.js"></script> <script type="text/javascript"> document.domain = "a.com"; var p = parent.window.$; p("#sub").text("我是子頁面添加的"); </script> </body> </html>
a.html就是要通過跨子域獲取數(shù)據(jù)的頁面:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <!-- 通過跨域獲取數(shù)據(jù),并添加到ul中 --> <ul id="data"></ul> <!-- 子頁面通過parent.window來訪問父頁面 --> <div id="sub"></div> <!-- 通過iframe引用img.a.com下的img.html --> <iframe id="iframe" src="http://img.a.com/img.html"></iframe> <script src="./jquery.js"></script> <script type="text/javascript"> document.domain = "a.com"; $("#iframe").bind("load", function() { //獲取子頁面的jquery對象 iframe = document.getElementById("iframe").contentWindow.$; iframe.getJSON("http://img.a.com/img.json", function(data) { var con = ""; //注意這里的$對象是www.a.com上的 $.each(data, function(i, v) { con += "<li>" + v.name + ":" + v.url + "</li>"; }); $("#data").html(con); }); }); </script> </body> </html>
a.html中我們通過contentWindow.$來獲取子頁面的jquery對象,然后通過getJSON獲取數(shù)據(jù),并通過www.a.com上的$對象把數(shù)據(jù)寫入到ul中。
在子頁面img.html中我們通過parent.window來訪問父頁面的$對象,并操作元素添加數(shù)據(jù)。
看完了這篇文章,相信你對“PHP中如何解決ajax跨子域的問題”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
分享文章:PHP中如何解決ajax跨子域的問題-創(chuàng)新互聯(lián)
文章URL:http://jinyejixie.com/article48/djsdhp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信小程序、網(wǎng)站維護(hù)、網(wǎng)頁設(shè)計(jì)公司、網(wǎng)站策劃、App設(shè)計(jì)、網(wǎng)站排名
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容