什麼情況下才會出現跨域?假設網域名稱是:http://www.example.com.cn/如果所請求的網域名稱跟這個網域名稱不致,這種情況就是跨域,由於跨域存在漏洞,所以一般來說正常的跨域請求方式是請求不到的。
解決方式:
一、window.name 1、 伺服器返回
<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的內容,注意必須進行同域處理後方可訪問! var data = document.getElementById('iframe1').contentWindow.name; alert(data); // {"id":"3", "name":"leisure"}
load = false; } } </script> 3、定義一個form,設定form的target為iframe的id,然後提交form <form action="url" method="POST" target="iframe1"> <button type="submit" value="submit" />
</form>
二、JSONP
伺服器返回 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
伺服器返回 json格式資料 test({"id": "3", "name": "leisure"}); test函數名為callback參數中定義 $.getJSON(url + "?callback=?", data, function(data) { } 注意callback=?這個參數必須帶上,jquery會自動產生一個函數名替換這個問號!jQuery.getJSON實際上是用了JSONP方式實現。
四、flash跨域 伺服器添加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>