Address: http://blog.csdn.net/hongweigg/article/details/6756278
1. jquery Ajax request. garbled characters are received in the background
You can explicitly set the contenttype encoding to UTF-8, and the background can be decoded normally, for example:
[JavaScript]
View plaincopyprint?
- Contenttype: "application/X-WWW-form-urlencoded; charset = UTF-8 ",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
[JavaScript]
View plaincopyprint?
- Jquery (form). ajaxsubmit ({
- URL: "dologin? User = ",
- Type: "Post ",
- Datatype: "JSON ",
- Contenttype: "application/X-WWW-form-urlencoded; charset = UTF-8 ",
- Success: showloginresponse
- });
jQuery(form).ajaxSubmit({url: "doLogin?user=a",type: "post",dataType: "json",contentType: "application/x-www-form-urlencoded; charset=utf-8",success: showLoginResponse});
If you use escape () without adding contenttype: "application/X-WWW-form-urlencoded; charset = UTF-8 ",
The post body contains fewer bytes than the specified content length.
.
2. garbled characters returned by jquery Ajax
Have you found that no matter how you set the encoding, the data received by the client is always garbled? Please refer to the following example. Do you find any problems?
[Java]
View plaincopyprint?
- VoidSavetempkind (httpservletrequest req, httpservletresponse resp)
- ThrowsServletexception, ioexception {
- Printwriter PW = resp. getwriter ();
- Resp. setcontenttype ("text/text; charset = GBK ");
- Try{
- // Do Process
- PW. Write ("successful ");
- }Catch(Exception e ){
- PW. Write ("failed ");
- }
- }
Void savetempkind (httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {printwriter PW = resp. getwriter (); resp. setcontenttype ("text/text; charset = GBK"); try {// do process PW. write ("succeeded");} catch (exception e) {PW. write ("failed ");}}
The problem is that resp. setcontenttype ("text/text; charset = GBK ");
The statement should be in
[JavaScript]
View plaincopyprint?
- Printwriter PW = resp. getwriter ();
PrintWriter pw = resp.getWriter();
Before, not after. As in the preceding example, no matter how you set the response encoding, the front-end garbled code remains the same. The possible cause is that the PW encoding is determined before obtaining the priintwriter. Therefore, the encoding declaration should be prior to obtaining the printwriter object.