美文网首页
Jsonp跨域

Jsonp跨域

作者: 李永州的FE | 来源:发表于2017-06-15 09:45 被阅读0次

1需要注意的是: 对于当前页面来说页面存放的 JS 文件的域不重要,重要的是加载该 JS 页面所在什么域

题目2: 什么是跨域?跨域有几种实现形式

  • 什么是跨域?
    允许不同域的接口进行交互
  • 跨域有几种实现形式
  1. JSONP
  2. CORS
  3. 降域
  4. postMessage

题目3: JSONP 的原理是什么

1 首先script标签呢可以访问任何src指向的位置,所以采用这种方式跨域
2 客户端要对返回的json字符串解析成html字符串显示,所以服务端返回的是back(data)这种形式的字符串,让客户端以函数形式执行
3 那么客户端怎么定义函数,服务端怎么知道返回什么函数名呢,就是以加在url后面的callback=函数名这样来约定,服务端拿到这个参数就知道了

题目4: CORS是什么

前端用 XMLHttpRequest 跨域访问时,浏览器会在请求头中添加:origin
后端会添加一个响应头:Access-Control-Allow-Origin
浏览器判断该相应头中Access-Control-Allow-Origin的值是否包含 Origin 的值,如果有则浏览器会处理响应,我们就可以拿到响应数据,如果不包含浏览器直接驳回,这时我们无法拿到响应数据。

题目5:3中跨域方式

  • 1 jsonp
客户端index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>news</title>
  <style>
    .container{
      width: 900px;
      margin: 0 auto;
    }
    ul,
    li {
        padding: 0;
        margin: 0;
        list-style: none;
    }
    body {
        font: 20px/1.5  Helvetica, arial, "Microsoft Yahei", "微软雅黑", STXihei, "华文细黑", sans-serif;
        background: #FF9279;
        padding: 50px;
        min-width: 550px;
    }
    .change{
      border: none;
      outline: none;
      margin: 30px;
      padding: 10px 20px;
      border-radius: 10px;
      background: #4A9DBB;
      font: 20px/1.5  "Microsoft Yahei", "微软雅黑", STXihei, "华文细黑", sans-serif;
      color: #FFF;
      cursor: pointer;
    }
    .news{
      background: #EF6100;
      padding: 30px 20px;
    }
  </style>
</head>
<body>
    <div class="container">
      <ul class="news">
        <li>第11日前瞻:中国冲击4金 博尔特再战</li>
        <li>男双力争会师决赛 </li> 
        <li>女排将死磕巴西!</li>
      </ul>
      <button class="change">换一组</button>
    </div>
    
  <script>
    
    $('.change').addEventListener('click', function(){
      var script = document.createElement('script');
      script.src = 'http://b.ji.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>';
      }
      $('.news').innerHTML = html;
    }
    function $(id){
      return document.querySelector(id);
    }
  </script>
</body>
</html>
服务端
app.get('/getNews', function(req, res){
    var news = [
        "第11日前瞻:中国冲击4金 博尔特再战200米羽球",
        "正直播柴飚/洪炜出战 男双力争会师决赛",
        "女排将死磕巴西!郎平安排男陪练模仿对方核心",
        "没有中国选手和巨星的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;
    if(cb){
        res.send(cb + '('+ JSON.stringify(data) + ')');
    }else{
        res.send(data);
    }
    })
  • 2 CORS
1     客户端
<body>
    <div class="container">
      <ul class="news">
        <li>中英上演奥运金牌大战</li>
        <li>没有中国选手和巨星的110米栏 我们还看吗? </li> 
        <li>下跪拜谢与洪荒之力一样 都是真情流露</li>
      </ul>
      <button class="change">换一组</button>
    </div>
    
  <script>
    
    $('.change').addEventListener('click', function(){
      var xhr = new XMLHttpRequest();
      xhr.open('get', 'http://b.ji.com:8080/getNews', true);
      xhr.send();
      xhr.onreadystatechange = function(){
        if(xhr.readyState === 4 && xhr.status === 200){
          appendHtml( JSON.parse(xhr.responseText) )
        }
      }
      window.xhr = xhr
    })
    function appendHtml(news){
      var html = '';
      for( var i=0; i<news.length; i++){
        html += '<li>' + news[i] + '</li>';
      }
      $('.news').innerHTML = html;
    }
    function $(id){
      return document.querySelector(id);
    }
  </script>
</body>
</html>
2     服务端
app.get('/getNews', function(req, res){
    var news = [
        "第11日前瞻:中国冲击4金 博尔特再战200米羽球",
        "正直播柴飚/洪炜出战 男双力争会师决赛",
        "女排将死磕巴西!郎平安排男陪练模仿对方核心",
        "没有中国选手和巨星的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", "http://a.ji.com:8080"); 
    //res.header("Access-Control-Allow-Origin", "*"); 
    res.send(data);
})
  • 3 postmessage
a.html      
<body>
  <div class="ct">
    <h1>使用postMessage实现跨域</h1>
    <div class="main">
      <input type="text" placeholder="http://a.ji.com:8080/a.html">
    </div>
    <iframe src="http://b.ji.com:8080/b.html" frameborder="0" ></iframe>
  </div>
  <script>
  $('.main input').addEventListener('input', function(){
    console.log(this.value);
    window.frames[0].postMessage(this.value,'*');
  })
  window.addEventListener('message',function(e) {
      $('.main input').value = e.data
      console.log(e.data);
  });
  function $(id){
    return document.querySelector(id);
  }
  </script>
</body>
</html>
b.html
<body>
    <input id="input" type="text"  placeholder="http://b.ji.com:8080/b.html">
    <script>
    $('#input').addEventListener('input', function(){
        window.parent.postMessage(this.value, '*');
    })
    window.addEventListener('message',function(e) {
            $('#input').value = e.data
        console.log(e.data);
    });
    function $(id){
        return document.querySelector(id);
    }
    </script>
</body>
</html>

相关文章

网友评论

      本文标题:Jsonp跨域

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