總結一些跨域的方式

一、可能平時最經常使用到的就是get方式的jsonp跨域,能夠用jquery提供的$.ajax 、$.getJSON。javascript

$.ajax({
    url:'接口地址',
    type:'GET',
    data:'想給接口傳的數據',
    dataType:'jsonp',
    success:function(ret){
        console.log(ret);
    }
});

這樣很簡單的就能夠實現jsonp的跨域,獲取接口返回值。php

想更多的瞭解$.ajax能夠參考下面的連接,裏面有很詳細的介紹:連接描述html

二、post方式的form表單跨域。java

a.com html:
<script>
function postCallback(data){}
</script>
<form acrion='接口連接' method='post' target='ifr'></form>
<iframe name='ifr'></iframe>
a.com callback.php:
<?php
header('Content-type: text/javascript');
echo '<script>';
//回調原頁面上函數處理返回結果
echo 'window.top.postcallback(' .$_GET['data']. ');';
echo '</script>';

b.com api.php:

<?php
//....
$data = '{"ret":0,"msg":"ok"}';
// ** 讓結果跳轉到a.com域 **
header("Location: http://a.com/callback.php?data=".urlencode($data));

三、CORS跨域node

原理:CORS定義一種跨域訪問的機制,可讓AJAX實現跨域訪問。CORS 容許一個域上的網絡應用向另外一個域提交跨域 AJAX 請求。實現此功能很是簡單,只需由服務器發送一個響應標頭便可。jquery

注:移動終端上,除了opera Mini都支持。ajax

利用 CORS,http://www.b.com 只需添加一個標頭,就能夠容許來自 http://www.a.com 的請求,下圖是我在PHP中的 hander() 設置,「*」號表示容許任何域向咱們的服務端提交請求:json

header("Access-Control-Allow-Origin:*");

也能夠設置指定域名:api

header("Access-Control-Allow-Origin:http://www.b.com");

js部分:跨域

$.ajax({
    url: a_cross_domain_url,
    crossDomain: true,
    method: "POST"
});

CORS比較適合應用在傳送信息量較大以及移動端來使用。

四、script標籤來跨域

<script src='訪問的接口地址'></script>
js.onload = js.onreadystatechange = function() {
    if (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') {
        // callback在此處執行
        js.onload = js.onreadystatechange = null;
    }
};

五、h5的postMessage

otherWindow.postMessage(message, targetOrigin);
otherWindow: 對接收信息頁面的window的引用。能夠是頁面中iframe的contentWindow屬性;window.open的返回值;經過name或下標從window.frames取到的值。
message: 所要發送的數據,string類型。
targetOrigin: 用於限制otherWindow,「*」表示不做限制
a.com/index.html中的代碼:

<iframe id="ifr" src="b.com/index.html"></iframe>
<script type="text/javascript">
window.onload = function() {
    var ifr = document.getElementById('ifr');
    var targetOrigin = 'http://b.com';  // 若寫成'http://b.com/c/proxy.html'效果同樣
                                        // 若寫成'http://c.com'就不會執行postMessage了
    ifr.contentWindow.postMessage('I was there!', targetOrigin);
};
</script>
b.com/index.html中的代碼:

<script type="text/javascript">
    window.addEventListener('message', function(event){
        // 經過origin屬性判斷消息來源地址
        if (event.origin == 'http://a.com') {
            alert(event.data);    // 彈出"I was there!"
            alert(event.source);  // 對a.com、index.html中window對象的引用
                                  // 但因爲同源策略,這裏event.source不能夠訪問window對象
        }
    }, false);
</script>

六、子域跨域(document.domain+iframe)

www.a.com上的a.html

document.domain = 'a.com';
var ifr = document.createElement('iframe');
ifr.src = 'http://script.a.com/b.html';
ifr.style.display = 'none';
document.body.appendChild(ifr);
ifr.onload = function(){
    var doc = ifr.contentDocument || ifr.contentWindow.document;
    // 在這裏操縱b.html
    alert(doc.getElementsByTagName("h1")[0].childNodes[0].nodeValue);
};
script.a.com上的b.html

document.domain = 'a.com';

具體的作法是能夠在http://www.a.com/a.htmlhttp://script.a.com/b.html兩個文件中分別加上document.domain = 'a.com';而後經過a.html文件中建立一個iframe,去控制iframecontentDocument,這樣兩個js文件之間就能夠「交互」了。固然這種辦法只能解決主域相同而二級域名不一樣的狀況。

相關文章
相關標籤/搜索