Ajax cross-Domain problem handling

Source: Internet
Author: User
Tags script tag domain server

This is a question that is often asked in interviews during this time. That is, if your front end wants to get the data under another domain name, how the front end needs to be requested and how the backend needs to be set.

There are two ways to handle the most common

Method one, set Response.setheader ("Access-control-allow-origin", "*") in Java code to solve the problem of cross-domain Ajax, where the asterisk represents the Allow all requests

$.ajax ({                  "post",           "Http://192.168.1.88/testAjaxJson",           "Application/json" ,           dataType:  "JSON",           function() {         alert ("request Succeed ");       });
@Controller Public classTestController {/*** Cross-domain requests using normal JSON *@paramResponse*/@RequestMapping (Value= "/testajaxjson")       Public voidTestajaxjson (httpservletresponse response) {Try {              //This is set to any domain request to get the dataResponse.setheader ("Access-control-allow-origin", "*"); //Here you can also set the Receive mode, the fixed domain two choose  OneResponse.setheader ("Access-control-allow-headers", "Accept, Content-type"); Response.setheader ("Access-control-allow-method", "POST"); Response.setheader ("Access-control-allow-origin", "http://192.168.1.88");
Response.getwriter (). Print ("{\" id\ ": 1}"); Response.flushbuffer (); } Catch(Exception e) {e.printstacktrace (); } } }

Before the official post, the browser makes an options request (also called preflight), with the header with Origin and access-control-request-*:* *, The server response will return the appropriate access-control-allow-origin, and if so, the browser will send a formal post, otherwise the above error will occur. This also answers the question of when cross-domain access, when we send a POST request, fails to see what Chrome network will find to be the options method.

The content-type here do not belong to any of the (Application/x-www-form-urlencoded,multipart/form-data,text/plain), so it is a complex request.

Complex request is the first option request, HTTP options request with GET, post, head, and so on, are the HTTP request method, the options method, to obtain a server-side URL support method, response Methods supported by the Allow flag in the header

The second time is the real request.

Method Two, request the data using JSONP, the backend needs to return the JS method call, the returned data is placed in the parameter

functionTestjsonp () {$.ajax ({URL:"Http://192.168.1.88/testAjaxJsonp", type:"GET",//must be a GET requestDataType: "Jsonp",//the requested data typeJSONP: "Callback",//request type is callbackJsonpcallback: "Callbackfunction",//method of callback when data request succeedsdata:{},//the requested dataSuccessfunction(data) {//execution of completed returned dataalert (data.id);//the output value is 1        }    });}
 Public class TestController {      @RequestMapping (value= "/testajaxjsonp")      publicvoid  callback, httpservletresponse response) {          try  {  
Here Jsonp returned data is fixed format after the text has a detailed explanation response.getwriter (). Print (callback+ "({\" id\ ": 1})"); Response.flushbuffer (); Catch (Exception e) { e.printstacktrace ();}} }
principle analysis of Jsonp cross-domain

  The most basic principle of JSONP is: adding a <script> tag dynamically, and the SRC attribute of the script tag is not a cross-domain limitation. In this way, this cross-domain approach is actually unrelated to the Ajax XMLHttpRequest protocol.

JSONP is an unofficial protocol that allows the server-side integration of script tags to return to the client, using the form of JavaScript callback for cross-domain access JSONP that is JSON with Padding. Due to the limitations of the same-origin policy, XMLHttpRequest only allows resources to be requested for the current source (domain name, protocol, port). If cross-domain requests are made, we can make cross-domain requests by using the HTML script tag and return the script code to execute in the response, where the JavaScript object can be passed directly using JSON. This cross-domain communication method is called JSONP.

Jsoncallback function jsonp123 (...): A callback function that is registered by the browser client and gets the JSON data on the cross-domain server

Jsonp principle:

First register a callback (for example: ' Jsoncallback ') on the client, and then pass callback's name (for example: jsonp123) to the server. Note: After the server gets the value of callback, use Jsonp123 (...). Include the JSON content that will be output, at which point the server generates JSON data to be properly received by the client.

Then, in JavaScript syntax, a function is generated, and the function name is the value of the parameter ' Jsoncallback ' that is passed up jsonp123

Finally, the JSON data is placed directly into the function in the form of a parameter, so that a document of JS syntax is generated and returned to the client.

The client browser, parses the script tag, and executes the returned JavaScript document, at which time the JavaScript document data, as parameters,
Passed into the client's pre-defined callback function (as in the previous example, the jquery $.ajax () method encapsulates the Success:function (JSON)). (Dynamic execution callback function)

Can say Jsonp way principle and <script src= "//cross-domain/...xx.js" ></script> is consistent (QQ space is a large number of this way to achieve cross-domain data exchange). JSONP is a script injection (scripts injection) behavior, so there are some security implications.

Note that Jquey is not supported for post-mode cross-domain.

Hope that the summary can help everyone

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.