一、Jsonp
現在有一個一段代碼
<script type="text/javascript" src="./testJsonp.php?callback=getInfo"></script>
那麼,後臺通過GET拿到參數callback,然後返回Js的代碼,後臺返回的內容會被當作Js解析
<?php
$callback = $_GET['callback'];
/*$data = {
"name":"ruiy",
"age":20
};*///php裏的對象不是這麼寫的
$data = array("name"=>"ruiy","age"=>20);
$data = json_encode($data);
echo $callback."($data)";
那麼前臺這裏寫好回調函數
function getInfo(res){
console.log(res);
alert(res.name+":"+res.age);
}
如果想動態地添加和訪問,那就動態的添加scrpt代碼,後臺代碼不變,前臺代碼testJsonp.html如下
Filename :testJsonp.html
<!DOCTYPE html>
<html>
<head>
<title>testJsonp</title>
</head>
<body>
<script type="text/javascript">
// 動態的加入script片段,以跨域訪問
var scriptTag = document.createElement("script");
scriptTag.setAttribute("type", "text/javascript");
scriptTag.setAttribute("src","./testJsonp.php?callback=getInfo");
document.getElementsByTagName("head")[0].appendChild(scriptTag);
function getInfo(res){
console.log(res);
alert(res.name+":"+res.age);
}
</script>
</body>
</html>
Jquery裏有$.getJson()的方法,有倆個參數,第一個是url,第二個是callback函數,實際上幫助我們省掉了添加script代碼等工作,即插即用,很方便
二、Access-Control-Allow-Origin:*
這段內容參考http://blog.csdn.net/linlzk/article/details/48028267
主要內容就是,服務器允許客戶端的訪問
在服務器端設置header,如
三、postMessage
這是html5的東西,有時間來研究一下
四、window.name
參考http://www.cnblogs.com/2050/p/3191744.html
主要就是,通過iframe的src引入跨域的頁面,但是原來頁面有不能跨域訪問iframe裏的東西,所以可以在iframe的onload設置iframe的src爲同一域名下,然後window的屬性卻沒有變,然後就可以訪問window.name了。這個有空來試,還沒有可供測試的其他域名。
看到一篇博客總結的蠻到位的,http://blog.csdn.net/kongjiea/article/details/44201021