PHP下ajax跨域的解決方案之window.name實例分析
本文實例講述了PHP下ajax跨域的解決方案之window.name。分享給大家供大家參考,具體如下:
原理核心:window對象的name屬性是一個很特別的屬性,當該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ù) -->
<div id="data"></div>
<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>
更多關于PHP相關內(nèi)容可查看本站專題:《PHP+ajax技巧與應用小結》、《PHP網(wǎng)絡編程技巧總結》、《php字符串(string)用法總結》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。
相關文章
使用Huagepage和PGO來提升PHP7的執(zhí)行性能
這篇文章主要介紹了使用Huagepage和PGO來提升PHP7的執(zhí)行性能的相關方案,來自于注明的PHP開發(fā)組成員Laruence的相關研究,需要的朋友可以參考下2015-11-11
PHP 常用數(shù)組內(nèi)部函數(shù)(Array Functions)介紹
本章節(jié)我們還要學習一些其它常用的有關數(shù)組的內(nèi)部函數(shù):count,sizeof、sort、asort、ksort等等,感興趣的朋友可以參考下哈,希望對大家有所幫助2013-06-06
iis6手工創(chuàng)建網(wǎng)站后無法運行php腳本的解決方法
下面小編就為大家?guī)硪黄猧is6手工創(chuàng)建網(wǎng)站后無法運行php腳本的解決方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06

