在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(){
});
}
);