在js中通過url傳值的時候會遇到中文亂碼問題,現解決方案如下:
傳值的時候用兩次encodeURI,在後台接收的時候再用URLDecoder.decode
參考代碼:
後台servlet:
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { String param = request.getParameter("userName"); if (param == null || param.length() == 0) { out.println("使用者名稱不可為空"); } else { String userName = URLDecoder.decode(param, "UTF-8"); if (userName.equals("somnl")) { out.println("使用者名稱[" + userName + "]已被註冊"); } else { out.println("你可以使用[" + userName + "]註冊"); } } } finally { out.close(); }}
前台js:
$(document).ready(function() { $("#verifyButton").click(function(){ var userName = $("#userName").val(); if(userName == ""){ alert("使用者名稱不可為空") }else{ $.get("UserVerify?userName=" + encodeURI(encodeURI(userName)),null,function(response){ $("#result").html(response); }); } }); $("#userName").keyup(function(){ }); });