Javascript跨域請求的4種解決方式

來源:互聯網
上載者:User

什麼情況下才會出現跨域
假設網域名稱是: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>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.