Home  >  Article  >  Web Front-end  >  Analysis of jsonp cross-domain access (front-end and back-end)

Analysis of jsonp cross-domain access (front-end and back-end)

不言
不言Original
2018-09-10 14:20:461428browse

The content of this article is about the analysis of jsonp cross-domain access (front-end and back-end). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. What is cross-domain access

Give a chestnut: In website A, we hope to use Ajax to obtain specific content in website B. If website A and website B are not in the same domain, then there will be a cross-domain access problem. You can understand that two domain names cannot send requests or request data across domain names, otherwise it will be unsafe. Cross-domain access violates the same-origin policy. For detailed information on the same-origin policy, you can click on the following link: Same-origin_policy; Domain name or IP) resources.

2. What is JSONP

JSONP (JSON with Padding) is a "usage mode" of JSON that can be used to solve the problem of cross-domain data access by mainstream browsers.

Due to the same-origin policy, generally speaking, web pages located at server1.example.com cannot communicate with servers other than server1.example.com, and the

3f1c4e4b6b16bbbd69b2ee476dc4f83a element of HTML is a exception. Using this open strategy of the 3f1c4e4b6b16bbbd69b2ee476dc4f83a element, web pages can obtain JSON data dynamically generated from other sources, and this usage pattern is the so-called JSONP. The data captured with JSONP is not JSON, but arbitrary JavaScript, which is executed with a JavaScript interpreter instead of parsed with a JSON parser. More specific principles require more space to explain, and you can go to Baidu by yourself.

3. Use of JSONP

Front-end usage example

JQuery Ajax encapsulates JSONP very well, and it is very convenient for us to use. Front-end example:

    $.ajax({
            type:"GET",
            url:"http://www.deardull.com:9090/getMySeat", //访问的链接
            dataType:"jsonp",  //数据格式设置为jsonp
            jsonp:"callback",  //Jquery生成验证参数的名称
            success:function(data){  //成功的回调函数
                alert(data);
            },
            error: function (e) {
                alert("error");
            }
        });

What needs to be noted is:

  • dataType, this parameter must be set to jsonp

  • jsonp , the value of this parameter needs to be agreed with the server, details are introduced below. (The conventional default value is callback)

Cooperation example of backend

JQuery Ajax Jsonp principle

To use jsonp in conjunction with the backend, you must first Understand a feature of Jquery Ajax jsonp:

When Jquery sends an Ajax jsonp request, it will automatically add a verification parameter after the access link. This parameter is randomly generated by Jquery, such as the link

http ://www.deardull.com:9090/getMySeat?callback=jQuery31106628680598769732_1512186387045&_=1512186387046 , parameter
callback=jQuery31106628680598769732_15121863 87045&_=1512186387046 is automatically added by jquery. The purpose of adding this parameter is to uniquely identify this request. When the server receives the request, it needs to construct the value of the parameter with the actual json value to be returned (how to construct it is explained below) and return it, and the front end will verify this parameter. If it is the parameter it sent before, then The data will be received and parsed. If it is not this parameter, then it will be rejected.
What needs special attention is the name of this verification parameter (I wasted 2 hours on this pit). This name comes from the value of the front-end
jsonp parameter. If the value of the front-end jsonp parameter is changed to "aaa", then the corresponding parameter should be aaa=jQuery311106628680598769732_1512186387045&_=1512186387046

Back-end reception and processing

I know Jquery Ajax Jsonp The principle and the parameters that need to be accepted are known, and we can write the server-side program.

In order to cooperate with json, what the server needs to do can be summarized into two steps:

The first step is to receive verification parameters
Receive verification according to the jsonp parameter name agreed with the front-end Ajax Parameters, examples are as follows (using SpringMVC, other languages ​​​​and frameworks have similar principles)

    @ResponseBody
    @RequestMapping("/getJsonp")
    public String getMySeatSuccess(@RequestParam("callback") String callback){

The second step is to construct parameters and return
Combine the received verification parameter callback with the actual json data to be returned Constructed according to the "callback(json)" method:

     @ResponseBody
    @RequestMapping("/getMySeat")    
    public String getMySeatSuccess(@RequestParam("callback") String callback){
        Gson gson=new Gson();   //google的一个json工具库
        Map<String,String> map=new HashMap<>();        
        map.put("seat","1_2_06_12");        
        return callback+"("+gson.toJson(map)+")";   //构造返回值
    }

IV. Summary

Finally, the corresponding code for the front and back ends should be like this:


Front end

    $.ajax({
            type:"GET",
            url:"http://www.deardull.com:9090/getMySeat", //访问的链接
            dataType:"jsonp",  //数据格式设置为jsonp
            jsonp:"callback",  //Jquery生成验证参数的名称
            success:function(data){  //成功的回调函数
                alert(data);
            },
            error: function (e) {
                alert("error");
            }
        });

Backend

    @ResponseBody
    @RequestMapping("/getMySeat")    
    public String getMySeatSuccess(@RequestParam("callback") String callback){
        Gson gson=new Gson();        
        Map<String,String> map=new HashMap<>();        
        map.put("seat","1_2_06_12");
        logger.info(callback);        
        return callback+"("+gson.toJson(map)+")";
    }

It should be noted that:

  • The front-end pays attention to communicating with the back-end to agree on the value of jsonp, usually the default All use callback.

  • After the backend obtains the parameters according to the jsonp parameter name, it must be constructed in a "callback(json)" manner with the json data to be returned.

  • If you want to test, remember to do it in a cross-domain environment (two machines).

The complete example is the above two pieces of code, which is valid for personal testing.

Related recommendations:

Cross-domain access JSONP CORS_html/css_WEB-ITnose

JSONP cross-domain GET request solves Ajax cross-domain Domain access problem_json

The above is the detailed content of Analysis of jsonp cross-domain access (front-end and back-end). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn