First, the use of JSONP:
Let's start with a simple version of how to use jquery's Ajax in the page to solve cross-domain issues:
$ (document). Ready (function () {varUrl='http://localhost:8080/WorkGroupManagment/open/getGroupById "+"? id=1&callback=? ';$.ajax ({url:url, DataType:'Jsonp', ProcessData:false, type:'Get', Success:function (data) {alert (data.name); }, Error:function (XMLHttpRequest, Textstatus, Errorthrown) {alert (xmlhttprequest.status); alert (xmlhttprequest.readystate); alert (textstatus); } });});
This is completely no problem, the first error handler function is only alert ("Error"), in order to further understand what caused the error, so the processing function into the above implementation. The last line of alert feedback parsererror the problem. Best of all, the reason is that the JSONP format is slightly different from the JSON format, so the code on the server side is a little differently.
Compare the differences between JSON and JSONP formats:
JSON format:
{ "message":"Get Success", " State":"1", "result":{"name":"Workgroup 1","ID":1,"Description":" One"}}
JSONP format:
Callback ({"message":"Get Success", " State":"1", "result":{"name":"Workgroup 1","ID":1,"Description":" One"}})
See the difference, in the URL callback to the background of the parameter is God horse callback is God horse, jsonp than JSON outside there is a layer of callback (). This will know how to deal with it, and then modify the background code.
The background Java code ends up as follows:
@RequestMapping (value ="/getgroupbyid") PublicString Getgroupbyid (@RequestParam ("ID") Long ID, httpservletrequest request, httpservletresponse response) throws IOException {String callback= Request.getparameter ("Callback"); Returnobject result=NULL; Group Group=NULL; Try{Group=Groupservice.getgroupbyid (ID); Result=NewReturnobject (Group,"Get Success", constants.result_success); } Catch(businessexception e) {e.printstacktrace (); Result=NewReturnobject (Group,"Get failed", constants.result_failed); } String JSON=Jsonconverter.bean2json (Result); Response.setcontenttype ("text/html"); Response.setcharacterencoding ("Utf-8"); PrintWriter out=Response.getwriter (); out. Print (Callback +"("+ JSON +")"); return NULL;}
Note: You need to convert the query results to my JSON format first, and then use the parameter callback to set another layer outside of the JSON and become Jsonp. Ajax that specifies a data type of JSONP can be further processed.
Although this solves the cross-domain problem, it is the cause of the parsererror caused by the review. The reason is that blindly the JSON format of data as the JSONP format of data for AJAX processing, resulting in this error, this time the server side code is this:
@RequestMapping (value ="/getgroupbyid") @ResponseBody PublicReturnobject Getgroupbyid (@RequestParam ("ID") Long id,httpservletrequest request, httpservletresponse response) {String callback= Request.getparameter ("Callback"); Returnobject result=NULL; Group Group=NULL; Try{Group=Groupservice.getgroupbyid (ID); Result=NewReturnobject (Group,"Get Success", constants.result_success); } Catch(businessexception e) {e.printstacktrace (); Result=NewReturnobject (Group,"Get failed", constants.result_failed); } returnresult;}//Error Handling methods
Second, JS set the header to achieve cross-domain access:
Restricted by the browser's same-origin policy, Javasript can only request resources within the domain. Cross-domain resource sharing (cross-origin Resource sharing, CORS) is a specification to solve the problem that Ajax technology is difficult to realize cross-domain, which tries to solve the problem of secure cross-domain resource sharing fundamentally. Before this, the way to solve such problems is often the server Agent, JSONP, etc., the symptom does not cure. The specification is now supported by all basic browsers.
A domain is composed of schema, host, and port, regardless of path. The so-called cross-domain refers to the resources on the http://example-bar.com/domain that are called on the http://example-foo.com/domain through the XMLHttpRequest object. Cors Conventions server-side and browser on the HTTP protocol, through some additional HTTP header information, cross-domain resource sharing negotiation. Both the server side and the browser must follow the requirements in the specification.
Cors divides HTTP requests into two categories, with different classes of cross-domain resource sharing negotiations based on different policies.
1. Simple cross-domain request.
The browser considers a simple cross-domain request when the HTTP request occurs in the following two scenarios:
1). The request method is or post, and when the request method is post, the Content-type must be application/x-www-form-urlencoded, multipart/ Form-data or a value in the Text/plain.
2). The request does not have a custom HTTP header.
For a simple cross-domain request, the browser is to add the Origin Header to the HTTP request, populate the domain where the JavaScript script resides, and request resources from the servers in the other domain. After a simple cross-domain request is received on the server side, the Access-control-allow-origin header is added to the response header based on the resource permissions configuration. After the browser receives the response, view the Access-control-allow-origin Header, and if the current domain has been authorized, return the result to JavaScript, otherwise the browser ignores the response.
2. Cross-domain request with pre-check (preflighted).
The browser considers a cross-domain request with a preflight (preflighted) when the HTTP request has the following two scenarios:
1). Except and post (with application/x-www-form-urlencoded, Multipart/form-data, Text/plain Content-type) Other than the HTTP method.
2). A custom HTTP header appears in the request.
cross-domain request with preflight (preflighted) requires the browser to send an options pre-check request before sending a real HTTP request. Detects whether the server side supports real requests for cross-domain resource access, and the actual requested information is passed through the Access-control-request-method header and access-control-request-headers in the options request Header description, in addition to the simple cross-domain request, the browser will also add the Origin Header. After the server has received the preflight request, the Access-control-allow-origin header is placed in the response header according to the resource permissions configuration. The Access-control-allow-methods and Access-control-allow-headers headers, respectively, represent the domains, request methods, and request headers that allow cross-domain resource requests. In addition, the server can also join the Access-control-max-age Header, allow the browser within a specified time, no need to send a pre-test request to negotiate, directly with the results of this negotiation. The browser determines whether to continue sending real requests for cross-domain resource access based on the results returned by the options request. This process is transparent to the caller of the real request.
XMLHttpRequest supports carrying identity information (credential, such as cookies or HTTP authentication information) across domain requests through the Withcredentials property. When the browser sends a request with a cookie header to the server side, the browser ignores the response if the server does not respond to the access-control-allow-credentials header.
the HTTP request discussed here is initiated by an Ajax XMLHttpRequest object, and all cors HTTP request headers can be populated by the browser without having to be set in the XMLHttpRequest object. The following is the HTTP header specified by the Cors protocol, which is used to negotiate when a browser initiates a cross-domain resource request:
1. Origin. HTTP request header, any request involving cors must be carried.
2. Access-control-request-method. HTTP request headers, which are used in cross-domain requests with preflight (preflighted) to represent real-world requests.
3. Access-control-request-headers. HTTP request header, a list of custom headers used in cross-domain requests with preflight (preflighted) to represent real requests.
4. Access-control-allow-origin. An HTTP response header that specifies the source domain on the server side that allows cross-domain resource access. You can use wildcards * to allow JavaScript for any domain to access resources, but in response to an HTTP request that carries identity information (credential), Access-control-allow-origin must specify a specific domain and cannot use wildcards.
5. Access-control-allow-methods. The HTTP response header, which specifies a list of request methods that the server allows for cross-domain resource access, is typically used in response to a preflight request.
6. Access-control-allow-headers. The HTTP response header, which specifies a list of request headers that the server allows for cross-domain resource access, is typically used in response to a preflight request.
7. Access-control-max-age. The HTTP response header, used in response to a preflight request, represents the effective time of this preflight response. During this time, the browser can decide whether it is necessary to send a real request directly, without having to send the preflight request again, based on the results of this negotiation.
8. Access-control-allow-credentials. HTTP response headers, which carry identity information in the browser request, and the response header does not return access-control-allow-credentials:true, the browser ignores the response.
Summary: whenever a cross-domain request is made with a custom header, an options request is sent before the real request is sent , and the browser decides whether to continue sending the real request for cross-domain resource access based on the results returned by the options request. So complex requests are sure to request the server two times.
JS end of the AJAX request:
$.ajax ({URL:"http://test.com", DataType:'JSON', type:'GET', Beforesend:function (XHR) {Xhr.setrequestheader ("Test","Testheadervalue"); }, Async:false, Cache:false, //contentType: ' application/x-www-form-urlencoded ',success:function (sresponse) {}});
Action on the service side:
//allow cross-domain accessHttpContext.Current.Response.AddHeader ("Access-control-allow-origin","*"); HttpContext.Current.Response.AddHeader ("Access-control-allow-methods","POST, GET, Options,delete,put"); HttpContext.Current.Response.AddHeader ("access-control-allow-headers","Test");
Solve Ajax cross-domain: 1, the use of Jsonp;2, JS set header