Jquery+jsp+servlet do $.ajax interaction when the Chinese garbled (character set problem) solution __js

Source: Internet
Author: User


Today in the $.ajax method of jquery to do asynchronous interaction with a very egg pain in Chinese garbled problem, toss for several hours, finally solved. Now I will elaborate on the solution of the problem.



My final code is as follows:



Code Snippet One: (Getresultservlet.java)

public static String decodeJqueryAjaxStr (String str) {
if (str == null || str.equals ("")) {
return "";
}
str = str.trim ();
try {
str = java.net.URLDecoder.decode (str, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace ();
}
return str;
}


public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType ("text / html; charset = utf-8");
request.setCharacterEncoding ("UTF-8");
PrintWriter out;
out = response.getWriter ();
// String text = decodeJqueryAjaxStr (request.getParameter ("mytxt"));
String text = request.getParameter ("mytxt");
// String text = new String (str.getBytes ("ISO-8859-1"), "UTF-8");
try {
JSONArray jsnarray = new JSONArray (); // Define JSON array
ArrayList <Questions> questions = questionDao.getInfoByName (text);
if (questions == null || questions.size () == 0) {
JSONObject obj = new JSONObject ();
obj.put ("trunk", "No related topic information exists!");
obj.put ("aopt", "");
obj.put ("bopt", "");
obj.put ("copt", "");
obj.put ("dopt", "");
obj.put ("ropt", "");
jsnarray.add (obj);
} else {
for (int i = 0; i <questions.size (); i ++) {
JSONObject obj = new JSONObject ();
Questions tmpQuestions = questions.get (i);
obj.put ("trunk", tmpQuestions.getTrunk ());
obj.put ("aopt", tmpQuestions.getAopt ());
obj.put ("bopt", tmpQuestions.getBopt ());
obj.put ("copt", tmpQuestions.getCopt ());
obj.put ("dopt", tmpQuestions.getDopt ());
obj.put ("ropt", tmpQuestions.getRopt ());
jsnarray.add (obj);
}
}
out.println (jsnarray);
out.flush ();
out.close ();
} catch (Exception e) {
e.printStackTrace ();
}
}
public void doPost (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet (request, response);
}
Code snippet two (javascript code):

function getinfolist (query) {
Ranch
if (query == "") {
alert ("Please enter search conditions.");
return;
}
$ .ajax ({
url: "/ taobaoexam / servlet / getResultServlet",
type: "post",
dataType: "json",
data: "mytxt =" + query,
beforeSend: function (XMLHttpRequest) {
$ ("# info"). empty ();
var $ htmlLi = $ ("<a id='loading' style='background-color:#FFFFCC'> Information loading ... </a>"); // Create DOM object
 $ ("# info"). append ($ htmlLi);
},
success: function (data, textStatus) {
$ ("# info"). empty ();
$ ("# info"). css ({"font-size": "12px"});
// The request was successful
$ (data) .each (function () {
var $ htmlLi = $ ("<hr /> <a style='background-color:#FFFFCC'>" + this.trunk + "</a>"); // Create a DOM object
var $ htmlLi1 = $ ("<br/> <a>" + this.aopt + "</a>");
var $ htmlLi2 = $ ("<br/> <a>" + this.bopt + "</a>");
var $ htmlLi3 = $ ("<br/> <a>" + this.copt + "</a>");
var $ htmlLi4 = $ ("<br/> <a>" + this.dopt + "</a>");
var $ htmlLi5 = $ ("<br/> <a style='background-color:#FFFFCC'> Correct answer:" + this.ropt + "</a>");
$ ("# info"). append ($ htmlLi);
$ ("# info"). append ($ htmlLi1);
$ ("# info"). append ($ htmlLi2);
$ ("# info"). append ($ htmlLi3);
$ ("# info"). append ($ htmlLi4);
$ ("# info"). append ($ htmlLi5);
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$ ("# info"). empty ();
 var $ htmlLi = $ ("<a style='background-color:#FFFFCC'> The page failed to load, please try again later. </a>"); // Create a DOM object
 $ ("# info"). append ($ htmlLi);
},
complete: function (XMLHttpRequest, textStatus) {
}
});
}

The get method I used at the beginning passed the local test. There will be no garbled Chinese characters, but it will not work on the server. It is very depressing. The code at the time was like this:

in javascript:

url: "/ taobaoexam / servlet / getResultServlet",
type: "get",
dataType: "json",
data: "mytxt =" + encodeURIComponent (query),
getResultServlet.java:
response.setContentType ("text / html; charset = utf-8");
request.setCharacterEncoding ("UTF-8");
PrintWriter out;
out = response.getWriter ();
String text = decodeJqueryAjaxStr (request.getParameter ("mytxt"));
// String text = request.getParameter ("mytxt");
// String text = new String (str.getBytes ("ISO-8859-1"), "UTF-8");
Compared with the above code, you can find the difference. In the beginning, I used the get method. On the javascript side, I used the encodeURIComponent method to encode Chinese characters. Then in the getResultServlet.java file, I used java.net.URLDecoder.decode Decode the coded Chinese characters that are transmitted. The local test passed. The server failed. Until now, I don't understand where the problem is. Please enlighten me.
After that, I changed it to the post method, and set the encoding of each part to utf-8.

The reference content is as follows:

[java] view plain copy <% @ page language = "java" pageEncoding = "UTF-8"%> <% @ page contentType = "text / html; charset = utf-8"%> <html> <head> < title> garbled </ title> <meta http-equiv = "Content-Type" content = "text / html; charset = UTF-8"> </ head> </ head> <body> required! garbled </ body > </ html>

This garbled problem is the simplest garbled problem. It is garbled caused by inconsistent page encoding.
Note that there are three sections of this page related to encoding settings:
The first encoding format is the storage format of the jsp file. Ecljpse saves files according to this encoding format. And compile the jsp file, including the Chinese characters inside.
The second is encoded in decoded format. Must be the same as the first one. The second line is in the iso8859-1 encoding format by default. So without this line, garbled characters will also appear. It must be consistent.
The third encoding is to control the decoding method of the browser. If the previous decoding is consistent and error-free, this encoding format does not matter. Some web pages are garbled because the browser cannot determine which encoding format to use. Because the page is sometimes embedded in the page, the browser confuses the encoding format. Garbled.
The second type: garbled characters when passing GET and POST parameters.

This garbled is also the internal encoding format of tomcat iso8859-1. When the post is submitted, if the encoding format of the submission is not set, it will be submitted as iso8859-1. The accepted jsp will be accepted as utf-8. . Causes garbled characters. For this reason, here are a few solutions and compare them.
A. GET request parameter processing
String str = new String (request.getParameter ("something "). getBytes (" ISO-8859-1 ")," utf-8 "); In this case, every parameter must be transcoded in this way. It is troublesome. But it does get Chinese characters.
B. POST request parameter processing

At the beginning of the processing request page, execute the requested encoding code, request.setCharacterEncoding ("UTF-8"), and set the character set of the submitted content to UTF-8. Use String str = request.getParameter ("something"); you can get Chinese character parameters. But every page needs to execute this sentence.

My situation belongs to the second type, because the request is submitted using Ajax, so the parameters passed are encoded according to the Ajax standard. The Ajax post method uses utf-8 encoding to submit parameters by default, so set the Ajax Content-Type request header to "application / x-www-form-urlencoded; charset =" utf-8 "to notify The encoding used by the server and client to send parameters. In this way, the server can directly obtain the transcoded parameter value through String word = request.getParameter ("something") ;, eliminating the need for request. SetCharacterEncoding. Of course, also You can add request.setCharacterEncoding ("UTF-8") to the doPost method in the Servlet that processes the request, and the effect is the same.

Reference source: http://blog.csdn.net/kaihua_86/article/details/6025984

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.