Solution Rollup for Ajax Cross-domain problems (recommended) _ajax related

Source: Internet
Author: User
Tags ticket

This article will describe a small white from the encounter across the domain does not know is a cross-domain problem, to know that the cross-domain problem does not know how to solve, and then to solve the cross-domain problem, finally found two ways to solve the Ajax cross-domain problem of the whole process.

I don't know if it's a cross-domain problem

The cause is this, in order to reuse, reduce repetitive development, a separate development of a user rights management system, a total of other systems to obtain authentication and authorization information, for the moment called a system, call a system to B for example. Using AJAX to invoke the interface of a system system in B system (data format is JSON), at the time, it was particularly confusing to have access to the corresponding URL in a system to return JSON data normally, but using AJAX to request the same URL in the B system did not react as if nothing had happened. So repeatedly changed to go for a long time has not been able to solve, so help colleagues, reminders may be Ajax cross-domain problem, so the problem as a cross-domain problem to solve.

Knowing the cross-domain and not knowing how to fix it

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

Find a way to solve

Now we know how to solve cross-domain problems, and the rest is the details of implementation. Errors in the process of implementation can not be avoided. It's been a long time since Google made the mistake of not knowing the difference between JSON and JSONP two formats.

Let's take a look at a simple version of how to use jquery ajax to solve cross-domain problems in the page:

$ (document). Ready (function () {
var url= ' http://localhost:8080/WorkGroupManagment/open/getGroupById '
+ '? Id=1&callback=? ';
$.ajax ({
dataType: ' Jsonp ',
type: ' Get ',
success:function (data) {
alert (;
error:function (XMLHttpRequest, Textstatus, Errorthrown) {
alert ( Xmlhttprequest.status);
alert (xmlhttprequest.readystate);
alert (textstatus);

This writing is completely no problem, at first the error of the processing function is only alert ("Error"), in order to further understand what is the cause of the error, so the processing function into the implementation of the above. The last line of alert is used as; ParserError. Baffled, continue Google, eventually in the omnipotent StackOverflow found the answer, link here. The reason is that the format of the JSONP is slightly different from the JSON format, so it's slightly different on the server side of the code.

Compare the differences between JSON and JSONP formats:

JSON format:

' message ': ' Get success ',
' state ': ' 1 ',
' result ': {' name ': ' Workgroup 1 ', ' ID ': 1, ' description ': ' 11 '}

JSONP format:

Callback ({
"message": "Get Success",
"state": "1",
"result": {"name": "Workgroup 1", "id": 1, "description": "11"}

See the difference, in the URL callback to the background of the parameter is God horse callback is God horse, jsonp than JSON outside a layer, callback (). So you know what to do with it. The background code is then modified.

The background Java code is finally as follows:

@RequestMapping (value = "/getgroupbyid") public
String 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 = 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 a layer outside of JSON and become a JSONP. Ajax, which specifies a data type of JSONP, can be further processed.

Although this solves the cross-domain problem, it is also the reason why the parsererror is caused by the review. The reason for this error is that blindly JSONP data in JSON format as the data in the format of the AJAX process, which is what the server-side code is:

@RequestMapping (value = "/getgroupbyid")
@ResponseBody public
returnobject 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 = new Returnobject (group, "Get Success", constants.result_success);
} catch (Businessexception e) {
e.printstacktrace ();
result = new Returnobject (group, "Get Failed", constants.result_failed);
return result;

The first way to solve the Ajax Cross-domain problem is to settle.

Append a workaround

The pursuit of endless, in Google's process, inadvertently found a dedicated to solve the cross-domain problem of the jquery plug-in-jquery-jsonp.

There is a first way to base, the use of the JSONP plug-in is relatively simple, server-side code without any changes.

Take a look at how you can 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"). Text (current workgroup: ;
"error": function (d,msg) {
alert ("Could not find user" +msg);

Here are two ways to solve cross-domain problems.

Add: Ajax Cross-domain problem has three solutions:

1. Resolving Cross-domain problems through intermediate transition layers

(1) Through the Web Proxy server will be different domain applications unified through the proxy server isolation, all applications under a domain name. (e.g. Apache,nginx, etc.)

(2) Cross-domain security restrictions are the browser-side. There is no Cross-domain security restriction on the server side, so the work of "Cross-domain access" is done through the native server side in a similar httpclient manner.

2. Solve cross-domain problems through <script> tags

Note: All the tags that have the attribute "src" have cross-domain capabilities, such as <script>, , <iframe>


Foreground script:

<script type= "Text/javascript" > 
var flighthandler = function (data) { 
alert (' Your flight results are: ticket price ' + Data.price + ' Yuan, ' + ' + ' + ' + + ' Zhang. '); 
var url = "Http://"; 
var script = document.createelement (' script '); 
Script.setattribute (' src ', url); 
document.getElementsByTagName (' head ') [0].appendchild (script); 

Background data.jsp content:

<%@ page language= "java" pageencoding= "UTF-8"%> 
String callback = Request.getparameter (" Callback "); 
StringBuilder builder = new StringBuilder (); 
Builder.append (callback). Append ("({)). Append (" \ code\ ": \" ca1998\ ","). Append ("\" price\ ": 1780,"). Append ("\" Tickets\ ": 5"). Append ("});" 
; Out.println (Builder.tostring ()); 

Use the Jsonp of jquery to achieve Cross-domain access, as shown in the following example:

 <script type= "Text/javascript" > $ (function () {$.ajax ({type: "Get", Async:false , url: "", DataType: "Jsonp", Jsonp: "Callback", Jsonpcallback: "Fli Ghthandler ", Success:function (JSON) {alert (' You have enquiry to flight information: Ticket price: ' + Json.price + ' yuan, more votes: ' + + ' Zhang. 
}, Error:function () {alert (' fail '); 
}); </script> 

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.