How to handle Ajax garbled characters

Source: Internet
Author: User

I found a garbled problem on the Internet and found various versions. Now I found that all kinds of experiences are available...

Not to mention, the method of success is as follows:

1. Set page encoding everywhere. I have always set it to UTF-8. No exception is found;

2. For Ajax processing methods, see the source code.

$.ajax({type : "POST",contentType : "application/json",url : "ToHistoryServlet?handleFlag=add&sendPerson=" + sendPerson+ "&currentTime=" + currentTime() + "&message="+ encodeURIComponent(message) + "&recvPerson=" + recvPerson,dataType : 'json',success : function(result) {alert(result.d);}});

Note: A. Use the POST method;

B. Add encodeuricomponent before the Chinese character (encode the string as a URI component );

C. jquery is used in this example.

3. For details about how to handle servlet reception, see source code.

public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("UTF-8");String handleFlag = request.getParameter("handleFlag");Message msg = new Message();// handle chinese code dml@2012.8.29if (request.getParameter("message") != null) {msg.setMessage(new String(request.getParameter("message").getBytes("iso8859-1"), "UTF-8"));}msg.setRecvPerson(request.getParameter("recvPerson"));msg.setSendPerson(request.getParameter("sendPerson"));msg.setSendTime(request.getParameter("currentTime"));if (handleFlag.equals("add")) {HistoryHandle.addMessage(msg);} else if (handleFlag.equals("delete")) {HistoryHandle.deleteMessage(msg);}}

Note: A. Set the encoding method request. setcharacterencoding to UTF-8;

B. js default encoding is iso8859-1, so need to convert a bit

String xxxxx=new String(request.getParameter("message").getBytes("iso8859-1"), "UTF-8")

The above operation can solve the Ajax garbled problem.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.