这里说的js跨域是指通过js在不同的域之间进行数据传输或通信,比如用ajax向一个不同的域请求数据,或者通过js获取页面中不同域的框架中(iframe)的数据。只要协议、域名、端口有任何一个不同,都被当作是不同的域。
要解决跨域的问题,我们可以使用以下几种方法:
一、通过jsonp跨域
在js中,我们直接用XMLHttpRequest请求不同域上的数据时,是不可以的。但是,在页面上引入不同域上的js脚本文件却是可以的,jsonp正是利用这个特性来实现的。
例如:
//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金 博尔特再战200米",
"正直播男双力争会师决赛",
"女排将死磕巴西队",
"没有中国选手和110巨星的110米跨栏",
"中英上演奥运金牌大战",
"博彩赔率挺中国夺回第二",
"最“出柜”奥运?同性之爱闪耀里约",
"下跪拜谢与洪荒之力一样 都是真情流露"
]
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)+')');
})
在这个例子中,当点击按钮时,动态的创建了一个<script></script>
标签,然后指定该标签的src
为http://zhuwei.com:8080/getNews
,之后对该地址的内容作为参数执行appendHtml
函数。从而实现了点击按钮,随机切换三条新闻展示在页面中的功能。
二、CORS跨域
CORS全城是跨域资源共享,(Cross-Origin Resource Sharing),是一种ajax跨域请求资源的方式,支持现代浏览器,支持IE10及以上。实现方法:当使用XMLHttpRequest发送请求时,浏览器发现该请求不符合同源策略,会给该请求加入一个响应头:Origin,后台进行一系列处理,如果确定接受请求则在返回结果中加入一个响应头:Access-Control-Allow-Origin;浏览器判断该相应头中是否包含Origin的值,如果有则浏览器会有处理响应,我们就可以拿到响应的数据,如果不包含,浏览器就直接驳回,这时我们无法拿到响应数据。
//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金 博尔特再战200米",
"正直播男双力争会师决赛",
"女排将死磕巴西队",
"没有中国选手和110巨星的110米跨栏",
"中英上演奥运金牌大战",
"博彩赔率挺中国夺回第二",
"最“出柜”奥运?同性之爱闪耀里约",
"下跪拜谢与洪荒之力一样 都是真情流露"
]
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);
})
三、使用降域实现跨域
原理:相同主域名不同子域名下的页面,可以设置 document.domain 让它们同域
限制:
1.有其他页面 window 对象的引用。
2.二级域名相同。
3.协议相同。
4.端口相同。
使用方法就是将符合上述条件页面的 document.domain 设置为同样的二级域名。这样我们就可以使用其他页面的 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>降域实现跨域</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实现跨域
postMessage()方法允许来自不同源的脚本采用异步方式进行有限的通信,可以实现跨文本档、多窗口、跨域消息传递。
//a.zhuwei.com:8080/a.html代码:
<body>
<div class="ct">
<h1>postmessage实现跨域</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>
网友评论