Solution to Chinese garbled characters using Ajax in Java

Source: Internet
Author: User

There is a garbled problem when Ajax uses the POST method to submit data to the Java background. Many requests are set on the server side on the Internet. setcharacterencoding ("UTF-8") to solve this problem or change all the front-end background encoding into a UTF-8, however, this method cannot be implemented in your own project (later analysis may be due to the use of the encoding filter ). After several days of exploration, I finally got it done:
1. the escape or encodeuri method is used for Ajax submission. Must be used twice
2. Java uses the decode method of the java.net. urldecoder class in the background.

Front-end Page code:
/**
* Marging is a JS object used to carry part of the page functions and parameters.
* XMLHTTP is the modified Ajax object, and the attribute paramstring is the parameter sent to the server in post mode.
* The front-end and back-end pages all adopt GBK encoding and use the encoding filter.
*/
XMLHTTP. paramstring = "mname =" + marging. mnames;
// The parameter is encoded with encodeuri twice
XMLHTTP. paramstring = encodeuri (XMLHTTP. paramstring );
XMLHTTP. paramstring = encodeuri (XMLHTTP. paramstring );
// Send a save request
VaR xmlreq = XMLHTTP. gettextbypost ("mailmerginged. jsp ");

Background Page code:
/**
* When the request. getparameter () function is called, The URI decoding process is automatically performed.
* Built-in decoding may cause garbled Characters During the call. After the URI is encoded twice, the request. getparameter () function
* The original information URI is encoded once. Use the controllable decoding function java.net. urldecoder. Decode ()
* The original correct information can be obtained.
*/
String mname = java.net. urldecoder. Decode (request. getparameter ("mname"), "UTF-8 ");

 

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.