JQuery Jsonp cross-domain request explanation

Source: Internet
Author: User

Cross-domain security restrictions are for the browser side, there is no cross-domain security restrictions on the server side.

The browser's same-origin policy restricts the interaction of documents or scripts loaded from one source with resources from another source.

If the protocol, port and host for two pages is the same, then two pages have the same source, otherwise it is not homologous.

If you want to initiate cross-domain requests in JS, you have to do some special processing. Alternatively, you can send the request to your server, initiate the request through the background code, and return the data to the front end.

Here's how Jsonp, using jquery, initiates cross-domain requests and their rationale.

First look at the preparation environment: Two ports are not the same, constituting a cross-domain request condition.

Get data: The port to get the data is 9090

Request data: The port of the request data is 8080

1, first look at the direct launch of the AJAX request will be what

The following is the code that initiates the request side:

1 <%@ page pageencoding= "Utf-8" contenttype= "Text/html;charset=utf-8"  language= "java"%> 2 

The results of the request are as follows: cross-domain requests can be seen because the browser's same-origin policy is blocked.

2. Next, see How to initiate cross-domain requests. There are a number of ways to resolve cross-domain requests, and here are just a few of the jsop ways and principles of jquery.

First we need to understand that it is not possible to launch a cross-domain Ajax request directly on the page, but it is possible to introduce a JS script on a different domain on the page, just as you can use the tag on your own page to display the image on a field at will.

For example, I request a 9090-port picture on the 8080 Port page: You can see that cross-domain requests directly through SRC are possible.

3, then see how to use <script src= "" > To complete a cross-domain request:

When clicking the "Get Data Across Domains" button, add a <script> tag to initiate cross-domain requests; Notice that the request address is followed by a callback=showdata parameter;

ShowData is the callback function name, which is passed to the background for wrapping data. The data is returned to the front end, which is the form of showdata (result), because it is a script, so the ShowData function is called automatically, and result is the parameter of ShowData.

At this point, we are cross-domain data request back, but it is troublesome, it is necessary to write a script to initiate the request, and then write a callback function to process the data, not very convenient.

1 <%@ page pageencoding= "Utf-8" contenttype= "Text/html;charset=utf-8"  language= "java"%> 2 

Service side:

1 protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {2     response.setcharacterencoding ("UTF-8"); 3     response.setcontenttype ("Text/html;charset=utf-8"); 4  5     //Data 6     list<student> studentlist = Getstudentlist (); 7  8  9     Jsonarray jsonarray = Jsonarray.fromobject (studentlist), ten     String result = jsonarray.tostring ( );     the callback function name passed by the front end is     String callback = Request.getparameter ("callback"), and/     /The return data is wrapped with a callback function name so that The return data is passed back as a parameter to the callback function.     result = callback + "(" + result + ");     response.getwriter (). write (result); 18}

Results:

4, then look at the Jsonp way of jquery cross-domain request:

Service-side code is the same, JS code is as follows: The simplest way, simply configure a datatype: ' Jsonp ', you can initiate a cross-domain request. JSONP Specifies that the server returns a data type of JSONP format, can see the originating request path, automatically with a callback=xxx,xxx is jquery randomly generated a callback function name.

The success here is like the showdata above, and if there is a success function the default success () is the callback function.

 1 <%@ page pageencoding= "Utf-8" contenttype= "Text/html;charset=utf-8" language= "java"%> 2 

Effect:

And look at how to specify a specific callback function: line 30th code

callback function you can write to <script> (the default belongs to the Window object), or to write to the Window object, look at the jquery source code, you can see JSONP call callback function, is called the Window.callback.

Then look at the result of the call, found that the request with the parameter is: callback=showdata; Call the callback function, the first call to the specified ShowData, and then call the success. So, success is a function that must be called after a successful return, and it depends on how you write it.

 1 <%@ page pageencoding= "Utf-8" contenttype= "Text/html;charset=utf-8" language= "java"%> 2 

and see how to change the name of callback: 23rd line of code

After you specify the name callback, the background needs to be changed as well.

 1 <%@ page pageencoding= "Utf-8" contenttype= "Text/html;charset=utf-8" language= "java"%> 2 

Background code:

1 protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {2     response.setcharacterencoding ("UTF-8"); 3     response.setcontenttype ("Text/html;charset=utf-8"); 4  5     //Data 6     list<student> studentlist = Getstudentlist (); 7  8  9     Jsonarray jsonarray = Jsonarray.fromobject (studentlist); ten     String result = jsonarray.tostring ();     the callback function name passed by the front end is     String callback = Request.getparameter ("Thefunction"), and the     return data is wrapped with the callback function name, In this way, the return data is passed back as a parameter to the callback function, with the     result = callback + "(" + result + "),"     response.getwriter (). write (result); 18}

Finally see if JSONP supports post: Ajax requests Specify the POST method

As you can see, the JSONP mode does not support cross-domain requests for post, even if it is specified as post, it is automatically turned into get mode, and the back end is not requested if it is set to post.

The implementation of JSONP is actually the same way that the <script> script requests the address, just the Ajax Jsonp to the package, so it is conceivable that JSONP is not supported by the POST method.

 1 <%@ page pageencoding= "Utf-8" contenttype= "Text/html;charset=utf-8" language= "java"%> 2 

To add, return to the first: Cors head lacks "access-control-allow-origin".

Sometimes you find that everything else is fine, and this error occurs: This error means that the server denies cross-domain access. If this error occurs, you will need to set the Allow cross-domain request on the server side.

Response.setheader ("Access-control-allow-origin", "*"); setting allows any domain name to be accessed across domains

Settings can be accessed across domains: the 6th line of code or the 8th line of code, set one of them.

1 protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {2     response.setcharacterencoding ("UTF-8"); 3     response.setcontenttype ("Text/html;charset=utf-8"); 4  5     6     response.setheader ("Access-control-allow-origin", "*") to allow any domain name to be accessed across domains, 7     //Specifies that a specific domain name can be accessed 8     Response.setheader ("Access-control-allow-origin", "http:localhost:8080/"); 9     //Data     list<student> studentlist = Getstudentlist ();     Jsonarray Jsonarray = Jsonarray.fromobject (studentlist);     String result = jsonarray.tostring ();     the callback function name     from the front end String callback = Request.getparameter ("callback"); The return data     is wrapped with a callback function name so that the return data is passed back as a parameter to the callback function.     Callback + "(" + result + ")"; "     Response.getwriter (). write (result); 22}

Summary: The jQuery ajax approach initiates cross-domain requests with the JSONP type, in the same way as the <script> script request, so you can only use get to initiate cross-domain requests when using JSONP. Cross-domain requests require a server-side mate, set up callback, to complete cross-domain requests.

JQuery Jsonp cross-domain request explanation

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.