JSONP跨域请求

什么是跨域:

1、域名不同

2、域名相同端口不同

js出于对安全考虑不支持跨域请求。我们可以使用JSONP解决跨域问题。

一、JSONP是什么

JSONP(JSON with Padding)是JSON的一种“使用模式”,可用于解决主流浏览器的跨域数据访问的问题。由于同源策略,一般来说位于 server1.example.com 的网页js是无法与不是 server1.example.com的服务器沟通,而 HTML 的<script> 元素是一个例外。利用 <script> 元素的这个开放策略,网页可以得到从其他来源动态产生的 JSON 资料,而这种使用模式就是所谓的 JSONP。用 JSONP 抓到的资料并不是 JSON,而是任意的JavaScript,用 JavaScript 直译器执行而不是用 JSON 解析器解析。

原理:浏览器在js请求中,是允许通过script标签的src跨域请求,可以在请求的结果中添加回调方法名,在请求页面中定义方法,既可获取到跨域请求的数据。(js请求的不是一个单纯的json数据而是一段包含json数据的js脚本)

 

二、模拟JSONP

服务器域名:http://localhost:8081/rest/itemcat/list

客户端服务器:http://localhost:8082/test.html

1、普通的JS跨域请求

服务器数据:

客户端请求代码:

    $(function(){
        $.ajax(
                {url: "http://localhost:8081/rest/itemcat/list?callback=myFunction", 
                 success: function(data){
                     console.info(data)
          }}); 
    });
    

结果

XMLHttpRequest cannot load http://localhost:8081/rest/itemcat/list?callback=myFunction. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8082' is therefore not allowed access.

2、模拟JSONP请求

客户端请求代码:

$(function(){
        greateScript("http://localhost:8081/rest/itemcat/list");
        function greateScript(src) {
            $("<script><//script>").attr("src", src).appendTo("body")
        } 
    });

结果:

list?_=1488425374097:1 Uncaught SyntaxError: Unexpected token :

 

三、使用JSONP

环境:

  服务器域名:http://localhost:8081/rest/itemcat/list

  客户端服务器:http://localhost:8082/test.html

服务端代码(本人使用springmvc4):

@RequestMapping("/itemcat/list")
    @ResponseBody
    public Object getItemCatList(String callback) {
        CatResult catResult = itemCatService.getItemCatList();
        MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(catResult);
        //设置JSONP回调函数
        mappingJacksonValue.setJsonpFunction(callback);
        return mappingJacksonValue;
    }

客户端调用代码:

$(function(){
        $.ajax(
            {   url: "http://localhost:8081/rest/itemcat/list", 
                dataType: "jsonp",
                jsonp: "callback",
                success: function(data){
                console.info(data)
          }});  
    });

结果:

 

看返回结果可以发现返回的数据不是一段单纯的json数据,而是一段js函数。

 

posted @ 2017-03-02 11:46  小禾点点  阅读(1235)  评论(0编辑  收藏  举报