1. Solution to Chinese garbled characters using $.ajax:
1. Test environmentjQuery:1.3.2
2. Test method
1. Use the get method
$.get("2.jsp", { name: "Chinese" },function(response){ alert(response);});Result: Correctly displayed
$.get(" 2.jsp", "name=中文",function(response){
alert(response);
});
Result: Garbled code
2.post method
Server-side java code:
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
Client js code:
$.ajax({url: "3.jsp",type: "post", data: "method=testAjaxPost&name=中文",success: function(response){
alert(response);
}});
Result:
$.ajax({url: "3.jsp",type: "post ",data: {name:"中文"},success: function(response){
alert(response);
}});
Result: Correct display
$.post("3.jsp", { name: "Chinese " },function(response){
alert(response);
});
Result: Correctly displayed
$.post("3.jsp", "name=中文",function(response){
alert(response ; >
The code is as follows:
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
if (req.getHeader("X-Requested-With") != null && req.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest")) {
When jQuery uses ajax, it will add X-Requested-With in the header. The value is: XMLHttpRequest. When the filter determines that it is jQuery's ajax request, the character encoding is set to utf8. This can solve the problem of Chinese garbled characters in post submissions. , there is no need to set request.setCharacterEncoding("UTF-8") in the code;
For the problem of Chinese garbled characters in the get method, it is recommended not to use the get method to submit Chinese, but to post instead. ^-^
In order to be consistent with the way prototype.js handles Chinese, you can use the following method to customize the attribute RequestType in the header
Copy code
The code is as follows:
$.ajax({
url: "3.jsp",
type: "post",
data: {name:"中文"},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("Error: " textStatus);
},
complete: function(XMLHttpRequest, textStatus){
alert("Complete:" textStatus);
}
});
filter代码如下:
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
if (req.getHeader("RequestType") != null && req.getHeader("RequestType").equalsIgnoreCase("ajax"))) {
request.setCharacterEncoding("utf-8");
} else {
request.setCharacterEncoding("gbk");
}
chain.doFilter(request, response);
}