AJAX Chinese problems fall into two categories:
1) the parameters in the sending path are in Chinese, and the received parameter values in the server segment are garbled.
For example:
Var url = "a. jsp? Name = Xiao Li ";
XmlHTTP. open ("post", url, true );
Solution:
Use the escape () or encodeURI () method provided by javascript
For example:
Client:
Var url = "a. jsp? Name = Xiao Li ";
Url = encodeURI (url );
Url = encodeURI (url); // twice, it is critical [I am not sure why]
/*************************************** *****/
Someone also writes var url = "a. jsp? Name = escape ("Xiao Li ")";
The function is similar to the encodeURI method.
/*************************************** *****/
XmlHTTP. setrequestheader ("cache-control", "no-cache ");
XmlHTTP. setrequestheader ("Content-Type", "application/x-www-form-urlencoded ");
XmlHTTP. setrequestheader ("contentType", "text/html; charset = uft-8") // specify the encoding format of the sent data
XmlHTTP. open ("post", url, true );
Server:
String name = request. getParameter ("name ");
Name = java.net. URLDecoder. decode (name, "UTF-8 ");
2) The returned value of responseText or responseXML contains Chinese characters which are garbled.
Cause: AJAX decodes responseText or responseXML values in UTF-8 format if the data sent by the server segment is not in UTF-8 format, the value of responseText or responseXML may be garbled.
Solution: Specify the data sending format on the server:
On the server:
Copy codeThe Code is as follows:
Response. setCharacterEncoding ("UTF-8 ");
Response. setContentType ("text/text; charset = UTF-8"); // The txt text file is returned.
Response. setContentType ("text/xml; charset = UTF-8"); // The returned xml file
Response. setContentType ("application/json"); // return the json File
PrintWriter bw = response. getWriter (); // This class is used for output
Bw. write (result );
Bw. flush ();
Bw. close ();
Conclusion: 1) ajax submits data in UTF-8 format by default, using the escape () or encodeURI () method provided by javascript. use java.net. URLDecoder. decode ("", "UTF-8") method for decoding.
2) The default character encoding of data returned by xtmlhttp is UTF-8. Therefore, the server must use UTF-8 encoding when sending data to the client.
If the above method still cannot solve the garbled problem, then you try to save jsp, htm, java file in UTF-8 encoding format.
In short: the front and back-end data interaction uses UTF-8 encoding.