AJAX传值时采用的是UTF-8编码格式,客户端中文字符传输到服务器端时,如果服务器编码格式或者所采用的MVC框架的编码格式不是UTF-8,则很可能会出现中文乱码。解决办法如下:
客户端用js函数encodeURI()对中文字符进行两次编码,服务器端采用URLDecoder类对客户端传输过来的中文字符进行UTF-8格式的解码。示例:
客户端代码:
$.ajax({
type: "post",
url: "createNewGroup.action",
data:"name="+encodeURI(encodeURI("张三")),
success: function(msg){
alert(msg);
}
});
服务器端代码:
String name = URLDecoder.decode("客户端传输过来的中文字符","UTF-8");
服务器端往客户端传输中文字符出现乱码时,服务器端可采用URLEncoder类对中文字符进行UTF-8格式的编码。客户端采用js函数decodeURI()对服务器端传输过的中文字符进行两次解码。
当服务器端传输的是一个json串时,且不可对整个json串进行UTF-8格式的编码(编码后的json串有可能不再具有json原有格式),可采用JsonValueProcessor接口和JsonConfig类对json串中的value进行单独编码。
示例代码:
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(String.class,
new JsonValueProcessor(){
public Object processArrayValue(Object value, JsonConfig jsonConfig) {
return process(value);
}
public Object processObjectValue(String key, Object value,
JsonConfig jsonConfig) {
return process(value);
}
/**
* process
* @param value
* @return
*/
public Object process(Object value) {
try {
if (value instanceof String) {
return URLEncoder.encode(value.toString(), "UTF-8");
}
return value == null ? "" : value.toString();
} catch (Exception e) {
return "";
}
}
});
JSONArray json = JSONArray.fromObject("[{name:\"张三\";age:\12\";sex:\"男\"}]",
jsonConfig
); //编码后的json串
客户端使用函数decodeURI()再对json串中的value值进行两次解码即可。