Ajax(4):post請求之表單中含有中文時如何處理

來源:互聯網
上載者:User

當採用post方式向伺服器發送請求時,並且表單中被輸入了中文時,往往會出現亂碼的狀況。

解決的方法: 在接收請求的Servlet中加上如下代碼:

request.setCharacterEncoding("UTF-8");

對於利用Ajax發送post請求,瀏覽器統一使用UTF-8進行編碼。此行代碼的作用就是以編程的方式指定讓Tomcat伺服器以UTF-8進行解碼,這樣編碼和解碼就保持了一致。

測試代碼如下:

register.jsp :

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%><html><head><title>Insert title here</title><script type="text/javascript" src="js/prototype1.6.js"></script><script type="text/javascript">function getXmlHttpRequest(){var xhr=null;if((typeof XMLHttpRequest)!='undefined'){xhr=new XMLHttpRequest();}else{xhr=new ActiveXObject("Microsoft.XMLHttp");}return xhr;}function valiUsername(){var xhr=getXmlHttpRequest();xhr.onreadystatechange=function(){if(xhr.readyState==4){if(xhr.status==200){var doc=xhr.responseText;document.getElementById('username_msg').innerHTML=doc;}else{document.getElementById('username_msg').innerHTML="系統錯誤...";}}else{document.getElementById('username_msg').innerHTML="驗證中...";}}var url="valiusername.do";xhr.open("post",url,true);xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");xhr.send("username="+document.getElementById('n1').value);}</script></head><body><form action="register.do" method="post">姓名:<input type="text" name="username" id="n1" onblur="valiUsername();"><span style="color:red" id="username_msg"></span><br>密碼:<input type="password" name="password"><br><input type="submit" value="註冊"></form></body></html>

UsernameServlet.java :

public class UsernameServlet extends HttpServlet {public void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("UTF-8");String uri=request.getRequestURI();String path=uri.substring(uri.lastIndexOf("/"),uri.lastIndexOf("."));response.setContentType("text/html;charset=UTF-8");PrintWriter pw=response.getWriter();if(path.equals("/valiusername")){String username=request.getParameter("username");System.out.println("姓名:"+username);if(username.equals("格林")){pw.println("使用者名稱已經佔用");}else{pw.println("使用者名稱可以使用");}}if(path.equals("/register")){String username=request.getParameter("username");String password=request.getParameter("password");response.sendRedirect("login.jsp");}}}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.