前端解決跨域問(wèn)題的8種方案(最新最全)
1) 在www.a.com/a.html中:document.domain = 'a.com';var ifr = document.createElement('iframe');ifr.src =
1) 在www.a.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 ; };
2) 在www.script.a.com/b.html中:
document.domain = 'a.com';
這個(gè)沒(méi)什么好說(shuō)的,因?yàn)閟cript 標(biāo)簽不受同源策略的限制。
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')});
//我們請(qǐng)求的內(nèi)容在哪里?
//我們可以在chorme 調(diào)試面板的source 中看到script 引入的內(nèi)容
,原理是利用
location.hash 來(lái)進(jìn)行傳值。
假設(shè)域名a.com 下的文件cs1.html 要和cnblogs.com 域名下的cs2.html 傳遞信息。
1) cs1.html首先創(chuàng)建自動(dòng)創(chuàng)建一個(gè)隱藏的iframe ,iframe 的src 指向cnblogs.com 域名下的cs2.html 頁(yè)面
2) cs2.html響應(yīng)請(qǐng)求后再將通過(guò)修改cs1.html 的hash 值來(lái)傳遞數(shù)據(jù)
3) 同時(shí)在cs1.html 上加一個(gè)定時(shí)器,隔一段時(shí)間來(lái)判斷l(xiāng)ocation.hash 的值有沒(méi)有變化,一旦有變化則獲取獲取hash 值
注:由于兩個(gè)頁(yè)面不在同一個(gè)域下IE 、Chrome 不允許修改parent.location.hash 的值,所以要借助于a.com 域名下的一個(gè)代理iframe
代碼如下:
先是a.com 下的文件cs1.html 文件:
function startRequest(){
var ifr = document.createElement('iframe');
ifr.style.display = 'none';
ifr.src = 'http://www.cnblogs.com/lab/cscript/cs2.html#paramdo'; document.body.appendChild(ifr);
}
function checkHash() {
try {
var data = location.hash ? location.hash.substring(1) : '';
if (console.log) {
console.log('Now the data is ' data);
}
} catch (e) {};
}
setInterval(checkHash, 2000);
cnblogs.com 域名下的cs2.html:
//模擬一個(gè)簡(jiǎn)單的參數(shù)處理操作
switch (location.hash){
case '#paramdo':
,callBack();
break ;
case '#paramset':
//do something……
break ;
}
function callBack(){
try {
parent.location.hash = 'somedata';
} catch (e) {
// ie、chrome 的安全機(jī)制無(wú)法修改parent.location.hash ,
// 所以要利用一個(gè)中間的cnblogs 域下的代理iframe
var ifrproxy = document.createElement('iframe'
);
ifrproxy.style.display = 'none';
ifrproxy.src = 'http://a.com/test/cscript/cs3.html#somedata'; // 注意該文件在"a.com" 域下
document.body.appendChild(ifrproxy);
}
}
a.com 下的域名cs3.html
//因?yàn)閜arent.parent 和自身屬于同一個(gè)域,所以可以改變其location.hash 的值
parent.parent.location.hash = self.location.hash.substring(1);
window.name 的美妙之處:name 值在不同的頁(yè)面(甚至不同域名)加載后依舊存在,并且可以支持非常長(zhǎng)的 name 值(2MB )。
1) 創(chuàng)建a.com/cs1.html
2) 創(chuàng)建a.com/proxy.html,并加入如下代碼
3 在b.com/cs1.html中包含:
1) a.com/index.html中的代碼:
,2) b.com/index.html中的代碼:
CORS 背后的思想,就是使用自定義的HTTP 頭部讓瀏覽器與服務(wù)器進(jìn)行溝通,從而決定請(qǐng)求或響應(yīng)是應(yīng)該成功,還是應(yīng)該失敗。
IE 中對(duì)CORS 的實(shí)現(xiàn)是xdr
var xdr = new XDomainRequest();
xdr.onload = function (){
console.log(xdr.responseText);
}
xdr.open('get', 'http://www.baidu.com');
......
xdr.send(null );
,其它瀏覽器中的實(shí)現(xiàn)就在
xhr 中
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4){
if (xhr.status>= 200 &&xhr.status< 304 || xhr.status == 304){ console.log(xhr.responseText);
}
}
}
xhr.open('get', 'http://www.baidu.com');
......
xhr.send(null );
實(shí)現(xiàn)跨瀏覽器的CORS
function createCORS(method, url){
var xhr = new XMLHttpRequest();
if ('withCredentials' in xhr){
xhr.open(method, url, true );
}elseif (typeof XDomainRequest != 'undefined'){
var xhr = new XDomainRequest();
xhr.open(method, url);
}else {
xhr = null ;
}
return xhr;
}
var request = createCORS('get', 'http://www.baidu.com'); if (request){
request.onload = function (){
......
};
request.send();
}
JSONP 包含兩部分:回調(diào)函數(shù)和數(shù)據(jù)。
回調(diào)函數(shù)是當(dāng)響應(yīng)到來(lái)時(shí)要放在當(dāng)前頁(yè)面被調(diào)用的函數(shù)。
數(shù)據(jù)就是傳入回調(diào)函數(shù)中的json 數(shù)據(jù),也就是回調(diào)函數(shù)的參數(shù)了。
,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"})*/
//原理如下:
//當(dāng)我們通過(guò)script 標(biāo)簽請(qǐng)求時(shí)
//后臺(tái)就會(huì)根據(jù)相應(yīng)的參數(shù)(json,handleResponse)
//來(lái)生成相應(yīng)的json 數(shù)據(jù)(handleResponse({"data": "zhe"}))
//最后這個(gè)返回的json 數(shù)據(jù)(代碼) 就會(huì)被放在當(dāng)前js 文件中被執(zhí)行 //至此跨域通信完成
jsonp雖然很簡(jiǎn)單,但是有如下缺點(diǎn):
1)安全問(wèn)題(請(qǐng)求代碼中可能存在安全隱患)
2)要確定jsonp 請(qǐng)求是否失敗并不容易
web sockets是一種瀏覽器的API ,它的目標(biāo)是在一個(gè)單獨(dú)的持久連接上提供全雙工、雙向通信。(同源策略對(duì)web sockets不適用)
web sockets原理:在JS 創(chuàng)建了web socket之后,會(huì)有一個(gè)HTTP 請(qǐng)求發(fā)送到瀏覽器以發(fā)起連接。取得服務(wù)器響應(yīng)后,建立的連接會(huì)使用HTTP 升級(jí)從HTTP 協(xié)議交換為web sockt協(xié)議。
只有在支持web socket協(xié)議的服務(wù)器上才能正常工作。
var socket = new WebSockt('ws://www.baidu.com');//http->ws; https->wss socket.send('hello WebSockt');
socket.onmessage = function (event){
var data =event.data;
}
分類(lèi): JavaScript