JSONP跨域问题演示

跨域是什么?

首先说下同源,同源策略是浏览器的一种安全策略,所谓同源是指,域名,协议,端口完全相同。而跨域就是不同源 !

能够进行跨域的请求

一般a,img,link[rel=stylesheet],video,audio,等等能够发出请求的标签都可以实现跨域访问。但是这些标签不能得到返回的东西,所以一般不会用他们来请求资源。

常见的跨域处理方案

由于ajax先天设计的时候,不能实现跨域访问。所以就出现了处理跨域这样的问题。
① jsonp来处理跨域,下面用jquery来实现,关键代码如下:

$.ajax({
  type : "GET",
  url : "http://www.a.com/index.php?message=msg&callback=?",
  dataType : "jsonp",
  jsonp: 'callback',
  success : function(json){
      console.log(json.msg);
  }
});

② 服务端设置 Access-Control-Allow-Origin
我们使用nodejs来完成这一问题。服务端代码如下:

"use strict"
const http = require('http');
const server = http.createServer();

server.on('request',(req,res)=>{
    res.writeHead(200,{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"});
    res.write('ajax cross domain');
    res.end();
})

server.listen(3000,(err)=>{
  if(err){
    return console.log(err.message);
  }
  console.log('server is on');
})

浏览器端代码如下:

window.onload = function(){
  var xhr = new XMLHttpRequest();
  xhr.open("post","http://localhost:3000/");
  xhr.onreadystatechange=function(){
    if(xhr.readyState==4){
        if(xhr.status==200){
          console.log(xhr.responseText);
        }
    }
  }
  xhr.send(null);
}

使用http的形式访问客户端网页,那么就会输出不同源下返回的数据。
③ 其他跨域策略 iframe, window.postMessage(), window.name(较好的解决方案,值得推荐)等
详见: http://rickgray.me/2015/09/03/solutions-to-cross-domain-in-browser.html

④ 使用豆瓣的api,简单封装一个跨域请求函数:

<script>
    /* 封装数据  跨域url  params fn */
    function crossDomain(url,params,fn){
        var head = document.getElementsByTagName('head')[0];
        // 1. 处理回调函数
        var cbName = 'jsonp'+ (Math.random() * Math.random()).toString().substr(2) + new Date().getTime();
        /* 将回调函数挂载到window对象上 */
        window[cbName] = function(data){
            // 拿到并处理数据
            fn(data);
            // 拿到数据后remove掉
            //head.removeChild(scriptObj);
        }
        // 2. 解析url
        var qstring = '';
        for(var key in params){
            qstring += key + '=' + params['key'] + '&';
        }
        qstring += 'callback=' + cbName;
        url += '?' + qstring;
        // 3. 插入script
        var scriptObj = document.createElement('script');
        scriptObj.src = url;
        head.appendChild(scriptObj);
    }
</script>

<script>
    /*  使用  */
    crossDomain('http://api.douban.com/v2/movie/in_theaters',{},function(data){
        console.log(data);
    })
</script>

⑤ 使用grunt 或 gulp等构建工具进行请求转发,此处省略

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wang's Blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值