Tag: Write set color key false flow catch cal bit
Usually development I rarely write front-end code, including script JS, JavaScript, CSS, and so on, and the following author's situation is similar. Find the following methods, listed.
(http://www.cnblogs.com/sunxucool/p/3433992.html)
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: 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 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" id": 1, ": " 11 "}}
JSONP format:
Callback ({"Message":"Get success","state" 1" result" name": " Workgroup 1" id": 1, ": " 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 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 = 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;}
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);}});
Here are two ways to solve cross-domain issues.
Another approach, is Tomcat settings (http://www.cnblogs.com/joshualzb/p/5528205.html)
Target: The Tomcat server provides an interface that cannot be accessed in other domains and requires an additional access-control-allow-origin:*
There are many methods of direct configuration, but I have not succeeded, so I can write the interceptor myself.
1. Writing Interceptor Code
Create a new class, implement the filter interface, the code is as follows
12345678910111213141516171819202122232425 |
package com.itxc.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CORSFilter
implements Filter {
@Override
public void init(FilterConfig filterConfig)
throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
httpResponse.addHeader(
"Access-Control-Allow-Origin"
,
"*"
);
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
|
2. Configure Web. xml
123456789 |
<
filter
>
<
filter-name
>CorsFilter</
filter-name
>
<
filter-class
>com.itxc.filter.CORSFilter</
filter-class
>
</
filter
>
<
filter-mapping
>
<
filter-name
>CorsFilter</
filter-name
>
<
url-pattern
>/*</
url-pattern
>
</
filter-mapping
>
|
3. Remove the mess configuration you've previously configured for this feature.
Reprint: Cross-domain access