中文乱码问题,解决办法其实很简单,传之前encode,传之后decode。看相关源码片段:
servlet
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
PrintWriter pw = response.getWriter();
String userId = request.getParameter("userId");
String vcard = VcardHandle.queryVcard(userId);
pw.print(URLEncoder.encode(vcard, "UTF-8"));
pw.close();
}
JavaScript
$.ajax({
type : "POST",
contentType : "application/x-www-form-urlencoded; charset=utf-8",
async : false,
url : "VcardServlet?userId=" + userId,
dataType : 'text',
success : function(result) {
vcard = decodeURIComponent(result);
}
});
需要注意的是:JavaScript中encodeURI 不对下列字符进行编码:“:”、“/”、“;”和“?”,建议使用encodeURIComponent
dml@2013.1.8