這里說的js跨域是指通過js在不同的域之間進行數(shù)據(jù)傳輸或通信驳规,比如用ajax向一個不同的域請求數(shù)據(jù),或者通過js獲取頁面中不同域的框架中(iframe)的數(shù)據(jù)。只要協(xié)議医男、域名砸狞、端口有任何一個不同昨登,都被當(dāng)作是不同的域趾代。
要解決跨域的問題,我們可以使用以下幾種方法:
一、通過jsonp跨域
在js中禽捆,我們直接用XMLHttpRequest請求不同域上的數(shù)據(jù)時笙什,是不可以的。但是胚想,在頁面上引入不同域上的js腳本文件卻是可以的琐凭,jsonp正是利用這個特性來實現(xiàn)的。
例如:
//html代碼:
<ul id="ct" class="news">
<li>第11日前瞻:中國沖擊4金</li>
<li>男雙力爭會師決賽</li>
<li>女排死磕巴西隊</li>
</ul>
<a id="change" class="btn" href="#" >換一組</a>
<script>
document.querySelector('#change').addEventListener('click',function(){
var script = document.createElement('script');
script.src = 'http://b.zhuwei.com:8080/getNews?callback=appendHtml';
document.head.appendChild(script);
//document.head.removeChild(script);
})
function appendHtml(news){
var html ='';
for(var i=0;i<news.length;i++){
html+='<li>'+news[i]+'</li>';
}
console.log(html);
document.querySelector('#ct').innerHTML = html;
}
</script>
//router代碼:
app.get('/getNews',function(req,res){
var news = [
"第11日前瞻:中國沖擊4金 博爾特再戰(zhàn)200米",
"正直播男雙力爭會師決賽",
"女排將死磕巴西隊",
"沒有中國選手和110巨星的110米跨欄",
"中英上演奧運金牌大戰(zhàn)",
"博彩賠率挺中國奪回第二",
"最“出柜”奧運统屈?同性之愛閃耀里約",
"下跪拜謝與洪荒之力一樣 都是真情流露"
]
var data = [];
for(var i=0;i<3;i++){
var index = parseInt(Math.random()*news.length);
data.push(news[index]);
news.splice(index,1);
}
var cb = req.query.callback;
res.send(cb+'('+JSON.stringify(data)+')');
})
在這個例子中愁憔,當(dāng)點擊按鈕時孽拷,動態(tài)的創(chuàng)建了一個<script></script>
標(biāo)簽脓恕,然后指定該標(biāo)簽的src
為http://zhuwei.com:8080/getNews
,之后對該地址的內(nèi)容作為參數(shù)執(zhí)行appendHtml
函數(shù)。從而實現(xiàn)了點擊按鈕乃秀,隨機切換三條新聞?wù)故驹陧撁嬷械墓δ堋?br>
二肛著、CORS跨域
CORS全城是跨域資源共享,(Cross-Origin Resource Sharing)环形,是一種ajax跨域請求資源的方式策泣,支持現(xiàn)代瀏覽器,支持IE10及以上抬吟。實現(xiàn)方法:當(dāng)使用XMLHttpRequest發(fā)送請求時萨咕,瀏覽器發(fā)現(xiàn)該請求不符合同源策略,會給該請求加入一個響應(yīng)頭:Origin火本,后臺進行一系列處理危队,如果確定接受請求則在返回結(jié)果中加入一個響應(yīng)頭:Access-Control-Allow-Origin聪建;瀏覽器判斷該相應(yīng)頭中是否包含Origin的值,如果有則瀏覽器會有處理響應(yīng)茫陆,我們就可以拿到響應(yīng)的數(shù)據(jù)金麸,如果不包含,瀏覽器就直接駁回簿盅,這時我們無法拿到響應(yīng)數(shù)據(jù)挥下。
//html代碼:
<ul id="ct" class="news">
<li>第11日前瞻:中國沖擊4金</li>
<li>男雙力爭會師決賽</li>
<li>女排死磕巴西隊</li>
</ul>
<a id="change" class="btn" href="#" >換一組</a>
<script>
document.querySelector('#change').addEventListener('click',function(){
var xhr = new XMLHttpRequest();
xhr.open('get','http://b.zhuwei.com:8080/getNews',true);
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
appendHtml(JSON.parse(xhr.responseText))
}
}
})
function appendHtml(news){
var html ='';
for(var i=0;i<news.length;i++){
html+='<li>'+news[i]+'</li>';
}
console.log(html);
document.querySelector('#ct').innerHTML = html;
}
</script>
//router代碼:
app.get('/getNews',function(req,res){
var news = [
"第11日前瞻:中國沖擊4金 博爾特再戰(zhàn)200米",
"正直播男雙力爭會師決賽",
"女排將死磕巴西隊",
"沒有中國選手和110巨星的110米跨欄",
"中英上演奧運金牌大戰(zhàn)",
"博彩賠率挺中國奪回第二",
"最“出柜”奧運?同性之愛閃耀里約",
"下跪拜謝與洪荒之力一樣 都是真情流露"
]
var data = [];
for(var i=0;i<3;i++){
var index = parseInt(Math.random()*news.length);
data.push(news[index]);
news.splice(index,1);
}
res.header("Access-Control-Allow-Origin","*");
res.send(data);
})
三桨醋、使用降域?qū)崿F(xiàn)跨域
原理:相同主域名不同子域名下的頁面棚瘟,可以設(shè)置 document.domain 讓它們同域
限制:
1.有其他頁面 window 對象的引用。
2.二級域名相同喜最。
3.協(xié)議相同偎蘸。
4.端口相同。
使用方法就是將符合上述條件頁面的 document.domain 設(shè)置為同樣的二級域名瞬内。這樣我們就可以使用其他頁面的 window 對象引用迷雪。
//a.zhuwei.com:8080/a.html代碼:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
.ct{
width: 910px;
margin: auto;
}
.main{
float: left;
width: 450px;
height: 300px;
border: 1px solid #ccc;
}
.main input{
margin: 20px;
width: 200px;
}
.iframe{
float: right;
}
iframe{
width: 450px;
height: 300px;
border: 1px dashed #ccc;
}
</style>
</head>
<body>
<div class="ct">
<h1>降域?qū)崿F(xiàn)跨域</h1>
<div class="main">
<input type="text" placeholder="http://a.zhuwei.com:8080/a.html"></input>
</div>
<iframe src="http://b.zhuwei.com:8080/b.html" frameborder="0"></iframe>
</div>
<script>
//URL: http://a.jrg.com:8080/a.html
document.querySelector('.main input').addEventListener('input', function(){
console.log(this.value);
window.frames[0].document.querySelector('input').value = this.value;
})
document.domain = "zhuwei.com"
</script>
</body>
</html>
//b.zhuwei.com:8080/b.html代碼:
<html>
<style>
html,body{
margin: 0;
}
input{
margin: 20px;
width: 200px;
}
</style>
<input id="input" type="text" placeholder="http://b.zhuwei.com:8080/b.html">
<script>
// URL: http://b.jrg.com:8080/b.html
document.querySelector('#input').addEventListener('input', function(){
window.parent.document.querySelector('input').value = this.value;
})
document.domain = 'zhuwei.com';
</script>
</html>
通過降域 完成了跨域使a.zhuwei.com:8080/a.html
可以操作不同域名下的b.zhuwei.com:8080/b.html
四、postMessage實現(xiàn)跨域
postMessage()方法允許來自不同源的腳本采用異步方式進行有限的通信虫蝶,可以實現(xiàn)跨文本檔章咧、多窗口、跨域消息傳遞秉扑。
//a.zhuwei.com:8080/a.html代碼:
<body>
<div class="ct">
<h1>postmessage實現(xiàn)跨域</h1>
<div class="main">
<input type="text" placeholder="http://a.zhuwei.com:8080/a.html"></input>
</div>
<iframe src="http://b.zhuwei.com:8080/b.html" frameborder="0"></iframe>
</div>
<script>
//URL: http://a.jrg.com:8080/a.html
document.querySelector('.main input').addEventListener('input', function(){
window.frames[0].postMessage(this.value,'*');
console.log(this.value);
})
window.addEventListener('message',function(e){
document.querySelector('.main input').value = e.data
console.log(e.data)
})
</script>
</body>
</html>
//b.zhuwei.com:8080/b.html代碼:
<input id="input" type="text" placeholder="http://b.zhuwei.com:8080/b.html">
<script>
// URL: http://b.jrg.com:8080/b.html
document.querySelector('#input').addEventListener('input', function(){
window.parent.postMessage(this.value,'*');
})
window.addEventListener('message',function(e){
document.querySelector('#input').value = e.data
console.log(e.data)
})
</script>