In the browser, the XMLHTTPRequest object is used to send Chinese parameters to the server. If it is not processed by the browser or the server, Chinese garbled characters may occur. there are many solutions to this problem. However, Chinese characters are usually displayed in IE, but garbled characters are still displayed in other browsers (such as Firefox. garbled characters are solved in Firefox, but garbled characters occur when I return to IE. therefore, to solve Chinese garbled characters in popular browsersProgramBecome common.
There are two solutions to this problem:
1. encode the Chinese parameters to be passed on the browser.CodeAs follows:
XMLHTTP. Open ("Post", "ajaxservlet", true); // request parameter initialization
XMLHTTP. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded"); // set the request header here because the request method is post. (This code can be omitted if the request method is get)
XMLHTTP. Send ("name =" + encodeuri ("China"); // send parameters to the server
Code on the server:
Printwriter out = response. getwriter (); // gets the output stream object of response.
String name1 = request. getparameter ("name"); // obtain the request parameter whose key is "name ".
String name = urldecoder. Decode (name1, "UTF-8"); // decodes the obtained Parameter
Out. Print (name); // send data to the browser
2. encode the Chinese parameters to be passed on the browser. The Code is as follows:
XMLHTTP. Open ("Post", "ajaxservlet", true); // request parameter initialization
XMLHTTP. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded"); // set the request header here because the request method is post. (This code can be omitted if the request method is get)
XMLHTTP. Send ("name =" + encodeuri ("China"); // send parameters to the server
Code on the server:
Printwriter out = response. getwriter (); // gets the output stream object of response.
String name1 = request. getparameter ("name"); // obtain the request parameter whose key is "name ".
String name = new string (name1.getbytes ("ISO-8859-1"), "UTF-8"); // decodes the obtained Parameter
Out. Print (name); // send data to the browser
The above two methods can solve the garbled problem when passing Chinese parameters using the XMLHTTPRequest object in any browser and display Chinese characters correctly.
TheArticleReproduced from the network base camp: http://www.xrss.cn/Dev/AJAX/2007101717013.Html