I encountered the problem of Ajax garbled code today. I found some materials on the Internet for a long time and tried many methods. I am grateful for the correct method. Address: http://www.blogjava.net/hulizhong/archive/2007/04/21/112416.html
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:
In the JSP file:
Response. setcontenttype ("text/text; charset = UTF-8"); // The TXT text file is returned.
Or
Response. setcontenttype ("text/XML; charset = UTF-8"); // The returned XML file
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.