Jquery ajax Garbled text is a problem many friends have encountered. Today we will use examples to help you solve the problem of jquery ajax return value Garbled text. It is actually a little detail.
Jquery ajax garbledThis is a problem that many of my friends have encountered. Today, we use examples to help you solve the problem of garbled code about jquery ajax return values. In fact, they are all small details.
Instance Solution
Encodeuri (data) // note the encoding twice !!
$. Ajax ({
Type: "post ",
Url: url,
Data: data,
Contenttype: "application/x-www-form-urlencoded; charset = UTF-8 ",
Cache: false,
Success: viewajax. handle (this. pdomobj, this. div, url ),
Error: viewajax. error (this. pdomobj, this. div, url)
});
Java:
String queryvalue = java.net. urldecoder. decode (string) request. getparameter (querycode), "UTF-8 ");
Method 2
When ajax sends a request, the default encoding is UTF-8, and the front-end and server encoding must be unified. This is no longer a duplicate, but even so, it still happens ;;;;;
Webpage special effects: // pay attention to the following two transcodes. The server also performs two transcodes to obtain normal data.
$ ("# Querybyname"). click (function (){
Var name = encodeuri ($ ("# qname"). val ()));
$. Ajax ({
Type: "post ",
Url: "querybyname. action ",
Contenttype: "application/x-www-form-urlencoded; charset = UTF-8 ",
Data :{
Queryname: name
},
Success: function (msg ){
$ ("# Signwork" cmd.html (msg );
}
})
})
Server: struts2
String name = getqueryname ();
Name = java.net. urldecoder. decode (name, "UTF-8 ");
System. out. println ("action... bbbb" + name );
String name01 = java.net. urldecoder. decode (name, "UTF-8 ");
System. out. println (".......... cccc" + name01 );
The correct data is obtained only after two transcoding operations. The cause is analyzed;
It is said that another simple way is to set
Tomcat configures the configuration file server. xml
Uriencoding is OK.
Finally, I found the root cause of the problem. In fact, my struts2 configuration file encountered a little problem.
There is such a configuration information in the configuration file.
<Constant name = "struts. i18n. encoding" value = "UTF-8"> </constant>
This must be consistent with the page encoding. If ajax is used to send requests, the default UTF-8 encoding is used, but the backend struts configuration file is GBK, which makes me very depressed !! At last, garbled characters also appeared during the use of regular action commit, and the problem was discovered here. In fact, if you use UTF-8 encoding, there will be no garbled characters.