Home > Article > Web Front-end > What to do if jquery ajax utf-8 is garbled?
Jquery ajax utf-8 garbled solution: 1. Set the encoding of contentType to "utf-8" and the code to "contentType: "application/x-www-form-urlencoded;charset=utf-8 ""; 2. Set "resp.setContentType("text/text;charset=GBK");" before obtaining the PrintWriter object.
The operating environment of this tutorial: Windows 10 system, jquery3.2.1 version, Dell G3 computer.
jquery ajax utf-8 What to do if the code is garbled?
jQuery AJAX request garbled code and return garbled code
1. jQuery AJAX request is received as garbled code in the background
You can explicitly set the encoding of contentType to utf-8, background Generally, it can be decoded normally. For example:
contentType: "application/x-www-form-urlencoded; charset=utf-8",
jQuery(form).ajaxSubmit({ url: "doLogin?user=a", type: "post", dataType: "json", contentType: "application/x-www-form-urlencoded; charset=utf-8", success: showLoginResponse });
If you do not add contentType: "application/x-www-form-urlencoded; charset=UTF-8", and use escape(),
# will appear ##"The post body contains fewer bytes than the content length specifies" error. 2. jQuery AJAX returns garbled charactersHave you found that no matter how you set the encoding, the data received by the client is always garbled. Please look at the example below. Do you find any problems?void saveTempKind(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter pw = resp.getWriter(); resp.setContentType("text/text;charset=GBK"); try { //DO PROCESS pw.write("成功"); }catch(Exception e){ pw.write("失败"); } }The problem is resp.setContentType("text/text;charset=GBK"); The statement should be before
PrintWriter pw = resp.getWriter();, not after. If it is like the above example, no matter how you set the response encoding, the front-end garbled problem will still remain the same. The possible reason is that the encoding has been determined before pw obtains the PriintWriter. So the encoding statement should be before getting the PrintWriter object. Recommended learning: "
jQuery Video Tutorial
"The above is the detailed content of What to do if jquery ajax utf-8 is garbled?. For more information, please follow other related articles on the PHP Chinese website!