Sometimes we need to use AJAX to submit the value of form, so we need to use serialize () to get the value of the form, but the value obtained if there is Chinese, will be garbled, the reason and solution is as follows:
Reason:. Serialize () automatically invokes the encodeURIComponent method to encode the data
Workaround: Call decodeURIComponent (xxx,true); decode the data
Such as:
vardata=$ (' #addf '). Serialize ();
Data= decodeuricomponent (data,true);
This is the first common practice on the Internet, but it's not easy to try.
Use $ (form). Serialize () to get all the information for the form:
My settings:
1 Engineering code, Js,jsp,java set to UTF-8
2 JSP page encoding:
<%@ page language= "java" pageencoding= "UTF-8" contenttype= "text/html; Charset=utf-8 "%> <metahttp-equiv=" Content-type content= "Text/html;charset=utf-8"/>
3 JS in processing
encodeURI (encodeURI (data))///Note the two-time encoding.
4 Processing in Java classes
Response.setcharacterencoding ("UTF-8"); Response.setcontenttype ("Text/html;charset=utf-8"); Used to convey Chinese string java.net.URLDecoder.decode ((String) request.getparameter ("username") to the page, "UTF-8");
This is the second common practice on the web, but also the general JSP base coding settings. The feeling is to submit the form primarily for get, and I am now using spring MVC to bind the submitted form information directly to the object.
But the lack of Chinese garbled problems.
Source:
$.ajax ({
url:$ ("#form"). attr ("action"),
data:$ (' #form '). Serialize (),//form to submit
DataType: ' JSON ',
Success:function (data) {
if (data) {
Artdialog.alert (Data.message);
if (Data.succeed = = True) {
Gotoview (' <%=path%>/usermanage/getlist.do ');
}
}
}
});
The reason for the garbled characters is: Using AJAX requests, when the request type is not set, the default is the GET request method. And get request way of garbled processing to adopt
(String) Request.getparameter ("username"), "UTF-8") to avoid garbled problems by way of a separate transcoding of each Chinese language.
Workaround:
When submitting a form using AJAX serialization, be sure to submit the form using a POST request to avoid garbled problems.
$.ajax ({
Type: "POST",
url:$ ("#form"). attr ("action"),
data:$ (' #form '). Serialize (),//form to submit
DataType: ' JSON ',
Success:function (data) {
if (data) {
Artdialog.alert (Data.message);
if (Data.succeed = = True) {
Gotoview (' <%=path%>/usermanage/getlist.do ');
}
}
}
});