Two commonly used methods to solve AJAX Chinese garbled characters
1. EncodeURI on the client side (utf-8 does not need to be done, the default), and convert the iso-8859-1 encoding to utf-8 encoding on the server side
2. EncodeURI is performed twice on the client side and converted once on the server side.
The reason why the second method can solve the problem:
After two conversions, perform the first decoding in the first getparameter method. Because the solution is in English (the result after the first encode), there will be no problem; the second time, use the decode method of URLDecoder, So this problem can be solved normally. It should be noted that the decoding format needs to be specified as "utf-8" in the decode method. Many Chinese platforms do not use utf-8 (I guess it is gb2312), so the default conversion of decode is not necessarily utf-8.
The reason why the client is encoded twice and decoded only once on the server is because of Tomcat. In order to make programming convenient for programmers (get and post use the same code), Tomcat will automatically decode the encoding of the post, so there is one less handwritten decoding statement on the server side. The reason why we need to perform encoding and decoding again is because the automatic decoding operation of Tomcat is not necessarily decoded according to the encoding we want, but the codes decoded for English and other characters are the same no matter what platform they are on, so it can be Tomcat automatically interprets the result of the first encoding, and then manually interprets the encodeURI code once to obtain the format you need.
Supplement: Now I have observed the behavior of the browser again, and I feel that it is not the fault of Tomcat, because the Chinese displayed in the browser is not the encoded content. I am currently confused about these encoding issues. I hope to know this. Friends with knowledge in this area are welcome to give me advice!
Solve IE cache problem
Add a timestamp and want to check?
Solve proxy issues
Want to? Convert to $
Sample code:
Copy the code code as follows:
function verify() {
//Method 1 to solve the Chinese garbled problem. The data sent from the page side is encoded as an encodeURI, and the server segment uses new String(old.getBytes("iso8859-1"),"UTF-8");
//Method 2 to solve the Chinese garbled problem, the data sent from the page side is encoded twice, and the server segment uses URLDecoder.decode(old, "UTF-8")
var url = "AJAXServer?name=" + encodeURI(encodeURI($("#userName").val()));
url = convertURL(url);
$.get(url,null,function(data){
$("#result").html(data);
});
}
//Add a timestamp to the url address to fool the browser and not read the cache
function convertURL(url) {
//Get timestamp
var timstamp = (new Date()).valueOf();
//Splice the timestamp information into the url
//url = "AJAXServer"
if (url.indexOf("?") >= 0) {
url = url + "&t=" + timstamp;
} else {
url = url + "?t=" + timstamp;
}
return url;
}