1. 程式人生 > >what is 跨域?

what is 跨域?

and htm pen pla jsonp 局限性 什麽 至少 con

1. 什麽情況下會跨域

協議. 域名. 端口號 至少其中一個不相同, 在發生數據交互時, 即會產生跨域的現象.

2. 解決跨域時, 前端能做什麽?

如果是協議. 端口不同, 那前端還是歇歇吧, 啥都幹不了

  • 修改domain [此方法僅適用於主域名相同的情況]

例: 如下a.b兩個頁面需進行數據交互

a: www.zhuyu.com

b: www.bbb.zhuyu.com

在www.zhuyu.com/a.html中:

document.domain = ‘a.com‘;
var ifr = document.createElement(‘iframe‘);
ifr.src = ‘http://www.script.a.com/b.html‘;
ifr.display = none;
document.body.appendChild(ifr);
ifr.onload = function(){
    var doc = ifr.contentDocument || ifr.contentWindow.document;
    //在這裏操作doc,也就是b.html
    ifr.onload = null;
};

在www.script.a.com/b.html中:

document.domain = ‘a.com‘;
  • 動態創建script

    src屬性不受同源策略的限制
    ```
    function loadScript(url, func) {
    var head = document.head || document.getElementByTagName(‘head‘)[0];
    var script = document.createElement(‘script‘);
    script.src = url;

script.onload = script.onreadystatechange = function(){
if(!this.readyState || this.readyState==‘loaded‘ || this.readyState==‘complete‘){
func();
script.onload = script.onreadystatechange = null;
}
};

head.insertBefore(script, 0);
}
window.baidu = {
sug: function(data){
console.log(data);
}
}
loadScript(‘http://suggestion.baidu.com/su?wd=w‘,function(){console.log(‘loaded‘)});


- JSONP [ 只能處理get請求,不支持POST請求(局限性) ]

function handleResponse(response){
console.log(‘The responsed data is: ‘+response.data);
}
var script = document.createElement(‘script‘);
script.src = ‘http://www.baidu.com/json/?callback=handleResponse‘;
document.body.insertBefore(script, document.body.firstChild);
/handleResonse({"data": "zhe"})

/
//原理如下:
//當我們通過script標簽請求時
//後臺就會根據相應的參數(json,handleResponse)
//來生成相應的json數據(handleResponse({"data": "zhe"}))
//最後這個返回的json數據(代碼)就會被放在當前js文件中被執行
//至此跨域通信完成
//僅僅是客戶端使用jsonp請求數據是不行的,因為jsonp的請求是放在script標簽中的,和普通請求不同的地方在於,它請求到的是一段js代碼,如果服務端返回了json字符串,那麽瀏覽器是會報錯的。所以jsonp返回數據需要服務端做一些處理。
```

以上選自: http://blog.csdn.net/joyhen/article/details/21631833

what is 跨域?