Wex5-ajax cross-domain calls related knowledge-cors and Jsonp

Source: Internet
Author: User
Tags script tag what callback

HTTP://DOCS.WEX5.COM/AJAX-CROSS-DOMAIN/1, what is cross-domain

Cross-domain problem is caused by the browser security mechanism, JS can only access the same domain (the same protocol, domain name, port) content.

However, in our project development process, often encountered in a page of the JS code, need to go through Ajax to access another server and return data, this time will be subject to browser cross-domain security restrictions.

It is important to note that it is not subject to cross-domain restrictions to send requests to another server only through Ajax without requiring data to be returned. The browser simply restricts data that cannot access another domain, that is, it cannot access the returned data, and does not limit the sending of requests.

Let's talk about the most common solutions for cross-domain Ajax calls, first of all we'll prepare a test environment:

    1. A tomcat that can start normally, default port 8080;
    2. Download the sample code package Ajax-cors-jsonp.zip, extracted to Tomcat WebApps, the sample code package has test-client and test-service two folders, each containing our example of the client and server code;
    3. Simulate a multi-domain environment, modify the "C:\Windows\System32\drivers\etc\hosts" (if the file cannot be edited and saved, you need to remove the read-only in the file properties), append to the file content:

127.0.0.1 www.aaa.com
127.0.0.1 www.bbb.com

After you start Tomcat, in the browser, test each

Http://www.aaa.com:8080/test-client/index.html

Http://www.bbb.com:8080/test-client/index.html

Two pages are the same, but the address is different, is the click on the button after the Ajax to access the http://www.bbb.com:8080/test-service/add.jsp. However, when accessed from www.aaa.com:8080, the error is returned, that is, the browser does not allow the return data from the www.bbb.com:8080 server to be obtained through Ajax in www.aaa.com:8080 's pages.

When you look at the Tomcat console, you'll find that when you access from www.aaa.com:8080, the error is returned, but the server code is actually executed. This behavior verifies that cross-domain is a request, but the browser does not let us get the return data in JS for security reasons.

The test case is simple to pass in the a=15&b=10 two parameters, return two data and 25, code see:

Test-client/index.html

test-service/add.jsp

2. Cors Scheme

The Cors (cross-origin Resource sharing) scenario described in this section is a truly official solution for the cross-domain access scenario that was officially launched in 2014. The implementation of this scheme is very simple, simply to indicate whether cross-domain access is allowed in the header information returned by the server, and which domain access is allowed.

Next we visit

Http://www.aaa.com:8080/test-client/index_cors.html

It worked!!! Let's see what's changed in the code.

The difference between index_cors.html and index.html is that the address of the AJAX call is changed from add.jsp to add_cors.jsp, and we look at the difference between add.jsp and add_cors.jsp and find that only one line of code is added:

Response.setheader ("Access-control-allow-origin", "http://www.aaa.com:8080");

If you do not qualify the addresses for cross-domain access, you can set the domain name section to *:

Response.setheader ("Access-control-allow-origin", "*");

Summary:

The cors scheme is very simple to implement, as long as the service is labeled in the header to allow cross-domain access. However, due to the late launch of this scheme, IE9 and the following browsers do not support this mechanism.

IE9 and the following browsers control whether cross-domain data access is allowed in security settings:

The default is that the above option is disabled and needs to be enabled manually. Also, because jquery automatically determines that the current browser does not support cross-domain, we also need a line of code to let jquery support cross-domain Ajax:

$.support.cors = true;

3. JSONP Scheme

JSONP is not an official agreement, it is essentially a clever programming technique for acquiring JSON data across domains.

We first look at the implementation, JSONP in the implementation of a little more trouble than Cors, the front and back to a little match.

First run http://www.aaa.com:8080/test-client/index_jsonp.html, this page inside the Ajax backend request replaced by add_jsonp.jsp.

Next we'll parse the code:

In index_jsonp.html, we have a slight change in the parameters of the $.ajax:

    1. Type changed to GET,JSONP only support GET request, this parameter in the JSONP scene is actually can be ignored, even if changed to post, will still press get mode;
    2. DataType changed to JSONP, this parameter indicates to use JSONP method to call;
    3. JSONP: "X5callback", this parameter is actually a contract parameter name, used for the backend to obtain a callback function name according to the parameter name;
    4. Jsonpcallback: This parameter is used to specify the name of the callback function for the above parameter, and if not specified, jquery automatically generates a random function name.

In add_jsonp.jsp, we did a bit of processing in the final Data return section:

    1. First we get the name of the callback function according to the agreed parameter name;
      String callbackname = Request.getparameter ("X5callback");
    2. The returned content format is no longer just a JSON data, but a JS function call form: callback function name (JSON data)
      String Jsonpresult = String.Format ("%s (%s)", Callbackname, Jsonresult);

The front and back end needs to do the work is so many, but at this time the beginner must feel a bit confused, what is the callback function name exactly what is used? What callback functions do we not define? How does it work?

The simple addition of a debug will quickly solve this confusion, adding a debugger to the data that add_jsonp.jsp eventually returns:

String Jsonpresult = String.Format ("debugger;%s (%s)", Callbackname, Jsonresult);

Next we F12 launch Browser Developer tool, click the button will enter JS debugging.

At this point we see that the return is a call to the JS function, the function name is random, the function parameter is the JSON we constructed. Next, we enter window. function name in the console and we will find that this function is real!!!

What's going on here??? The original jquery so-called Jsonp mode is actually a dynamic creation of a <script> tag, the src attribute of the tag points to a URL (http://www.bbb.com:8080/test-service/add_ jsonp.jsp?x5callback=jquery18203749695811420679_1439276096319&a=15&b=10&_=1439276101932), In addition to this URL contains our A and b two parameters, also contains a x5callback parameter, the value of the parameter is the random function name. This script tag dynamically inserted into the current page, will naturally be the contents of our return as JS loaded into the current page (here we return to JS, the browser is not blocked, oh, the page can be loaded from any domain JS script):

debugger;jquery18203749695811420679_1439276096319 ({"Sum": 25})

After loading, according to the JS characteristics, the code will be executed immediately. jquery has previously created a global function with the name of a random function to receive the returned data, and then jquery eventually gives the return value to our success callback function through a series of logical code.

For jquery dynamic creation <script> related logic, you can track it in our case with jquery-1.8.2.js 8270 lines plus breakpoints.

Summary:

JSONP is a programming technique based on dynamically creating a script tag that enables you to get JSON data across domains.

Support for all current browsers, but in the implementation of the method requires the front-end code has a little agreement with.

However, be aware that because JSONP is loaded with the SRC attribute of the script tag, the parameter receives a URL-length limit that can only be applied to scenes with a few incoming parameter content.

4. Summary

The cors scheme is simple to implement and supports both get and post requests, but IE9 and the following browsers are not supported. At this time crossing to ask, so many browsers do not support, how to use this technology ah? Mobile phone Ah! All mobile browsers currently on the market support cors, and if you are providing cross-domain Services for your phone, cors is enough.

The JSONP scenario implementation requires a front-end mate, supports get requests, supports all browsers, and only incoming parameter content is limited by the URL length limit.

Download resource: Ajax-cors-jsonp.zip

Wex5-ajax cross-domain calls related knowledge-cors and Jsonp

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.