美文网首页
前端常用的实现跨域的方法

前端常用的实现跨域的方法

作者: zevei | 来源:发表于2017-03-26 15:17 被阅读0次

这里说的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>标签,然后指定该标签的srchttp://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>

相关文章

  • Javascript跨域整理

    在前端的JS请求中,跨域的问题经常存在,根据不同的实现原理,常见的跨域的方法如下: 一:前端的方式 1:在前端页面...

  • 前端常用的实现跨域的方法

    这里说的js跨域是指通过js在不同的域之间进行数据传输或通信,比如用ajax向一个不同的域请求数据,或者通过js获...

  • JSONP跨域

    JSONP原理及应用 之前的文章中简单介绍过前端可以实现的跨域方式,这次介绍一种更为常用的跨域方式,但这种跨域方式...

  • vue-cli proxyTable配置

    前端的跨域转发 后端不需要配置,前端就可以实现跨域 proxyTable 的通常配置 这样就可以实现基本的跨域转发...

  • 前端跨域问题

    B/S架构的项目中前端经常会遇到跨域问题,什么是跨域问题,常用的解决方法又有哪些呢?可能大多数人对跨域问题都只是一...

  • 跨域资源共享(CORS)

    由于浏览器的同源策略,跨域成为前端开发过程中一个不能绕过的部分,常用的跨域方法有 JSONP,CORS等 概述 目...

  • 什么是跨域?跨域有几种实现形式:

    跨域指的是跨过同源策略,实现不同域之间进行数据交互的过程叫跨域。跨域的实现形式主要有JSONP方法、CORS方法、...

  • 跨域

    跨域指的是跨过同源策略,实现不同域之间进行数据交互的过程叫跨域。跨域的实现形式主要有JSONP方法、CORS方法、...

  • web跨域解决方案

    围绕以下几点介绍: 什么是跨域? 常用的几种跨域处理方法? crossdomain.xml解决跨域问题 什么是跨域...

  • JavaScript - GET/POST及跨域方法

    xhr 原生方法请求 window fetch 方法 关于跨域 利用JSONP实现跨域调用 使用 CORS(跨域资...

网友评论

      本文标题:前端常用的实现跨域的方法

      本文链接:https://www.haomeiwen.com/subject/rugcottx.html