How to troubleshoot Ajax cross-domain issues

Source: Internet
Author: User

How to troubleshoot Ajax cross-domain issues (GO)

Since very few previous front-end code (haha, unqualified programmers AH), the recent project using JSON as a means of interaction between systems, natural accompanied with many Ajax requests, followed by the problem is to solve the cross-domain Ajax. This article will describe a small white from encountering cross-domain problems, to know that cross-domain issues do not know how to solve, and then to solve cross-domain problems, finally find two ways to solve the Ajax cross-domain problem of the whole process.

I don't know, it's a cross-domain.

The cause is this, in order to reuse, reduce duplication of development, developed a user rights management system alone, a total of other systems to obtain authentication and authorization information, for the moment called a system; Call a system for example B. In the B system, using AJAX to invoke the interface of a system system (data format JSON), it was particularly confusing, in a system to access the appropriate URL to return JSON data normally, but in B system using AJAX request the same URL is not a little reaction, as if nothing happened. So repeatedly changed to change to a long time have not been able to solve, so help colleagues, remind may be Ajax cross-domain problem, so the problem as a cross-domain problem to solve.

Cross-domain and don't know how to solve it

Knowing the exact cause of the problem, the rest is finding a way to solve the problem. Google for a long time, again under the guidance of colleagues know jquery Ajax has jsonp such properties can be used to solve cross-domain problems.

Find a way to solve

Now also know how to solve cross-domain problems, the rest is the implementation of the details. The implementation of the process of error or can not be avoided. Because do not understand JSON and JSONP two kinds of format difference, also made mistake, Google for a long time to solve.

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 () {var url= http:// Localhost:8080/workgroupmanagment/open/getgroupbyid "+" ?id=1&callback= ";  $.ajax ({url:url, Datatype:" jsonp  ProcessData: Span style= "color: #0000ff;" >false get< Span style= "color: #800000;" > ' 

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 alert is used as; ParserError. Think of the solution, continue Google, and ultimately in the almighty StackOverflow found the answer, link here. The reason is that the format of the JSONP is slightly different from the JSON format, so it differs somewhat from the server-side code.

Compare the differences between JSON and JSONP formats:

JSON format:
{"Message":"Get success","State 1 ", " result ": {" name " workgroup 1"  "id1, description 11< Span style= "color: #800000;" > "           
JSONP format:
Callback ({"Message":"Get success","State 1 ", " result ": {" name " workgroup 1"  "id1, description 11< Span style= "color: #800000;" > "           

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, callback (). So we know how to deal with it. Then modify the background code.

The background Java code ends up as follows:

@RequestMapping (value ="/getgroupbyid")Public String Getgroupbyid (@RequestParam ("Id") Long ID, httpservletrequest request, httpservletresponse response) throws IOException {String callback = Request.getpar Ameter ("Callback"); Returnobject result =Null; Group Group =Null;Try{Group =Groupservice.getgroupbyid (ID); result =New Returnobject (Group,"Get success", constants.result_success); }Catch(Businessexception e) {e.printstacktrace (); result =New Returnobject (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 that 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") @ResponseBodyPublic Returnobject Getgroupbyid (@RequestParam ("Id") Long ID, httpservletrequest request, httpservletresponse response) {String callback = Request.getparameter ("Callback"); Returnobject result =Null; Group Group =nulltry {Group =new returnobject (Group,  " get success  "catch (Businessexception e) {e.printstacktrace (); result = new returnobject (Group,  " get failed  "return      

This is the first way to solve the Ajax cross-domain problem.

Append a workaround

The pursuit of endless, in the process of Google, inadvertently found a dedicated to solve cross-domain problems of the jquery plugin-jquery-jsonp.

With the first approach, the use of the Jsonp plugin is simpler, and the server-side code requires no changes.

Take a look at how to use the JQUERY-JSONP plugin to solve cross-domain problems.

var url="Http://localhost:8080/WorkGroupManagment/open/getGroupById"    +"? id=1&callback=?"; $.jsonp ({"url: URL,  "success" : Function ( Data) {$ ( " #current-group  current workgroup:  "+data.result.name); },  "error" : function (d,msg) {alert ( "could not find user  "+msg); }}); 

How to troubleshoot Ajax cross-domain issues

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.