什么情況下才會出現(xiàn)跨域?
假設(shè)域名是:http://www.example.com.cn/
如果所請求的域名跟這個域名不致,這種情況就是跨域,由于跨域存在漏洞,所以一般來說正常的跨域請求方式是請求不到的。
解決方式:
一、window.name
1、 服務(wù)器返回
<script>window.name='{"id":"3", "name":"leisure"}';</script>
2、定義一個iframe,添加onload事件 <iframe id="iframe1" onload="iLoad"><iframe>
<script type="text/javascript">
var load = false;
function iLoad() {
if(load == false) {
// 同域處理,請求后會再次重新加載iframe
document.getElementById('iframe1').contentWindow.location = '/';
load = true;
} else {
// 獲取window.name的內(nèi)容,注意必須進(jìn)行同域處理后方可訪問!
var data = document.getElementById('iframe1').contentWindow.name;
alert(data); // {"id":"3", "name":"leisure"}
load = false;
}
}
</script>
3、定義一個form,設(shè)置form的target為iframe的id,然后提交form
<form action="url" method="POST" target="iframe1">
<button type="submit" value="submit" />
</form>
二、JSONP
服務(wù)器返回 callback({"id": "3", "name": "leisure"});
<script type="text/javascript">
function callback(data) {
alert(data);
}
</script>
<script type="text/javascript" src="http://www.example.com.cn/product.jsp?id=5&jsonp=callback"></script>
三、jQuery.getJSON
服務(wù)器返回 json格式數(shù)據(jù) test({"id": "3", "name": "leisure"}); test函數(shù)名為callback參數(shù)中定義
$.getJSON(url + "?callback=?", data, function(data) {
}
注意callback=?這個參數(shù)必須帶上,jquery會自動生成一個函數(shù)名替換這個問號!jQuery.getJSON實際上是用了JSONP方式實現(xiàn)。
四、flash跨域
服務(wù)器添加crossdomain.xml
http://www.example.com.cn/crossdomain.xml
<?xml version="1.0"?>
<cross-domain-policy>
<allow-access-from domain="*.another.com.cn" />
</cross-domain-policy>