A summary of Ajax cross-origin problems (recommended) and ajax

Source: Internet
Author: User

A summary of Ajax cross-origin problems (recommended) and ajax

This article describes how to resolve a cross-origin problem, from a problem that does not know cross-origin to a cross-origin problem, finally, we can find two methods to solve the problem of cross-origin ajax.

I don't know if this is a cross-origin issue.

This is the reason. In order to reuse and reduce repeated development, A separate user permission management system was developed to obtain authentication and authorization information from other systems; to call system A, use system B as an example. In system B, ajax is used to call the interface of system A (the data format is json). At that time, it was particularly confusing to access the corresponding url in system A to return json data normally, however, in system B, when ajax is used to request the same url, there is no response at all, as if nothing had happened. In this way, the problem could not be solved after a long time, so I asked my colleagues for help and reminded them that the problem may be caused by cross-origin ajax, So I solved the problem as a cross-origin problem.

Cross-origin is unknown

Find the exact cause of the problem, and find a solution to the problem. After google for a long time, I once again learned that jQuery's ajax has attributes such as jsonp, which can be used to solve cross-domain problems.

Find a solution

Now I know how to solve the cross-origin problem. The rest is the implementation details. Errors in the implementation process cannot be avoided. Google has not solved the problem for a long time because it does not understand the difference between json and jsonp formats.

First, let's take a look at the simple version of how to use jQuery ajax to solve cross-origin problems on the page:

$(document).ready(function(){var url='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);}});}); 

In this way, there is no problem in writing. At first, the error processing function is only alert ("error"). To further clarify what causes the error, therefore, the processing function is changed to the above implementation method. The last alert row is used as; parsererror. Finally, I found the answer in the omnipotent stackoverflow. The link is here. The reason is that the jsonp format is slightly different from the json format, so the code on the server side is slightly different.

Compare the differences between json and jsonp formats:

Json format:

{"Message": "obtained successfully", "state": "1", "result": {"name": "workgroup 1", "id": 1, "description": "11 "}}

Jsonp format:

Callback ({"message": "obtained successfully", "state": "1", "result": {"name": "workgroup 1", "id": 1, "description": "11 "}})

Let's see the difference. In the url, the parameter callback is passed to the backend, that is, Shenma callback is Shenma, and jsonp has a layer more than the json outside, callback (). In this way, you will know how to handle it. Then modify the background code.

The background java code is eventually 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, "obtained successfully", Constants. RESULT_SUCCESS);} catch (BusinessException e) {e. printStackTrace (); result = new ReturnObject (group, "failed to get", 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 result to my json format first, and then use the callback parameter to set another layer outside the json to become jsonp. Ajax with the data type specified as jsonp can be further processed.

Although this solves the cross-origin issue, we should review the cause of parsererror. The reason is that the data in json format is processed by ajax blindly as the data in jsonp format, causing this error. The server code is as follows:

@ RequestMapping (value = "/getGroupById") @ ResponseBodypublic ReturnObject reply (@ 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, "obtained successfully", Constants. RESULT_SUCCESS);} catch (BusinessException e) {e. printStackTrace (); result = new ReturnObject (group, "failed to get", Constants. RESULT_FAILED);} return result ;}

So far, the first way to solve ajax cross-origin problems has come to an end.

Append a solution

The pursuit is endless. In the process of google, we accidentally found a jQuery plug-in-jquery-jsonp specifically designed to solve cross-domain problems.

There is a foundation for the first method. It is easy to use the jsonp plug-in, and the server code does not need to be changed.

Let's take a look at how to use the jquery-jsonp plug-in to solve cross-origin problems.

Var url = "http: // localhost: 8080/WorkGroupManagment/open/getGroupById" + "? Id = 1 & callback =? "; $. Jsonp ({"url": url, "success": function (data) {$ ("# current-group "). text ("Current Workgroup:" + data. result. name) ;}, "error": function (d, msg) {alert ("cocould not find user" + msg );}});

So far, the two methods for solving cross-origin problems are all described.

Supplement: There are three solutions to Ajax cross-origin problems:

1. Solve cross-domain problems through intermediate transition layer

(1) The Web Proxy Server isolates applications in different domains through the proxy server. All applications are under one domain name. (Such as apache and nginx)

(2) Cross-origin security restrictions refer to cross-origin security restrictions for the browser. The server does not have cross-origin security restrictions. Therefore, the local server completes cross-origin access in a way similar to httpclient.

2. Use the <script> label to resolve cross-origin issues

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

Example:

Foreground script:

<Script type = "text/javascript"> var flightHandler = function (data) {alert ('your query flight result is: Fare '+ data. price + 'yuan, '+ 'remaining votes' + data. tickets +. ') ;}; Var url = "http://abc.com: 8080/AjaxCrossDomain/data. jsp? Code = coding 98 & callback = flightHandler "; var script = document. createElement ('script'); script. setAttribute ('src', url); document. getElementsByTagName ('head') [0]. appendChild (script); </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 jsonp of jquery to implement cross-origin access, for example:

<Script type = "text/javascript"> $ (function () {$. ajax ({type: "get", async: false, url: "http://abc.com: 8080/AjaxCrossDomain/jsonp/data. jsp ", dataType:" jsonp ", jsonp:" callback ", jsonpCallback:" flightHandler ", success: function (json) {alert ('flight info: Fare: '+ json. price + 'yuan, remaining ticket: '+ json. tickets +. ') ;}, Error: function () {alert ('fail') ;}}) ;}); </script>

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.