JSONP cross-domain access analysis (front-end and back-end)

Source: Internet
Author: User
Tags tojson

This article brings the content is about JSONP cross-domain access analysis (front-end and back-end), there is a certain reference value, the need for friends can refer to, I hope to help you.

One, what is cross-domain access

For a chestnut : In a site, we want to use Ajax to get specific content from the B site. Cross-domain access issues occur if the A site is not in the same domain as the B site. You can understand that two domain names cannot cross a domain name to send requests or request data, otherwise it is unsafe. Cross-domain access violates the same Origin policy, and the details of the same-origin policy can be accessed by clicking the following link: same-origin_policy;
In summary, the same-origin policy stipulates that the browser's Ajax can only access resources that are identical to its HTML page (the same domain name or IP).

Second, what is JSONP

JSONP (JSON with Padding) is a "usage pattern" of JSON that can be used to address cross-domain data access issues in mainstream browsers.

Because of the same-origin policy, Web pages that are generally located in server1.example.com cannot communicate with servers that are not server1.example.com, and HTML <script> elements are an exception. Using <script> This open strategy of the element, the Web page can get JSON data that is generated dynamically from other sources, and this usage pattern is called JSONP. The data captured with JSONP is not JSON, but arbitrary JavaScript, which executes with a JavaScript interpreter instead of parsing with a JSON parser. More specific principles need more space to explain, small partners can go to Baidu on their own.

Third, the use of JSONP

Examples of using the front end

JQuery Ajax is a good package for JSONP, which is handy for us to use. Front-end Example:

    $.ajax ({            type: "GET",            URL: "Http://www.deardull.com:9090/getMySeat",//access to the link            dataType: "Jsonp",  // The data format is set to Jsonp            Jsonp: "Callback",  //jquery generates the name of the validation parameter            success:function (data) {  ///Successful callback function                alert ( Data)            ,            error:function (e) {                alert ("Error");}        });

The areas to note are:

    • DataType, this parameter must be set to JSONP

    • JSONP, the value of this parameter needs to be associated with the server-side contract, described in detail below. (The default value is callback)

Example of a back-end mate

JQuery Ajax Jsonp principle

To use JSONP with the backend, you first need to understand one of the features of jquery Ajax Jsonp:
When you send an AJAX JSONP request, jquery automatically adds a validation parameter after the access link, which is randomly generated by jquery, such as a link
http://www.deardull.com:9090/getMySeat?callback=jQuery31106628680598769732_1512186387045&_=1512186387046
, the parameters callback=jQuery31106628680598769732_1512186387045&_=1512186387046 are automatically added by jquery.
The purpose of adding this parameter is to uniquely identify this request. When the server side receives the request, it needs to construct the value of the parameter with the JSON value actually to be returned (how to construct the following), and return, and the front end will validate the parameter, if it is issued before the parameter, then will receive and parse the data, if not this parameter, then refused to accept.
Special attention is given to the name of the validation parameter (I wasted 2 hours on the pit), which is derived from the value of the jsonp parameter of the front end. If the value of the front-end JSONP parameter is changed to "AAA", then the corresponding parameter should be
aaa=jquery31106628680598769732_1512186387045&_=1512186387046

Back-end reception and processing

Knowing the principle of jquery Ajax Jsonp and knowing the parameters that need to be accepted, we can write a server-side program.
To complement JSON, the server side needs to do something that can be summed up in two steps:

First step, receive validation parameters

Receive validation parameters based on the JSONP parameter name with the front-end Ajax conventions, as shown in the following example (using SPRINGMVC, similar to other languages and frameworks)

    @ResponseBody    @RequestMapping ("/getjsonp") public    String getmyseatsuccess (@RequestParam ("callback") String callback) {

Step two, construct the parameters and return

The validation parameters that are received are callback with the JSON data that is actually being returned as callback (JSON):

     @ResponseBody    @RequestMapping ("/getmyseat") public        String getmyseatsuccess (@RequestParam ("callback") String callback) {        Gson gson=new Gson ();   A JSON tool library for Google        map<string,string> map=new hashmap<> ();                Map.put ("Seat", "1_2_06_12");                Return callback+ "(" +gson.tojson (map) + ")";   Construct return value    }

Iv. Summary

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

    $.ajax ({            type: "GET",            URL: "Http://www.deardull.com:9090/getMySeat",//access to the link            dataType: "Jsonp",  // The data format is set to Jsonp            Jsonp: "Callback",  //jquery generates the name of the validation parameter            success:function (data) {  ///Successful callback function                alert ( Data)            ,            error:function (e) {                alert ("Error");}        });

Back end

    @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 is important to note that:

    • The front end notes the value of the JSONP with the back-end communication conventions, usually by default, with callback.

    • The backend is constructed by "callback (JSON)" with the JSON data that would otherwise be returned, after obtaining the parameters based on the JSONP parameter name.

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

The complete example is the above two pieces of code, the pro-test is effective.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.