今天在做Ajax后台验证的时候,向后台传递的中文出现了乱码,在服务器端拿出的值都是null,因为中文传递的时候有%等符号。虽然把页面编码,Tomcat编码都改成了UTF-8,还加了转码过滤器,但是还是失败了。后来不停的Google,才得到了正确解答。
原因是:
Cause:
- Generally we get this error when we try to add special characters like “%, @, $ .. etc” in the GET/POST request from Ajax Call.
- Since these characters are used to URL specific function like “&” id used to differentiate various URL parameters. This generates a “null” value for the parameter you will try to retrieve in Servlet.
客户端:
var url = "UserVlidate.jsp?loginName=" + idField.value;//在这里不能使用escape( idField.value)
url=encodeURI(url); //要写两次
url=encodeURI(url);
if(window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.open("GET", url, true);
服务器端:
String loginName = request.getParameter("loginName");
loginName = java.net.URLDecoder.decode(loginName,"UTF-8");
这样才能把问题解决了。