在做一个Ajax小demo的时候想要使用Ajax发出请求通过url的形式向服务器传递中文数据,却发现传到后台的中文数据变成了乱码,后尝试了一些方法,发现最好用的方法是如下:使用js中的encodeURL()函数将中文进行两次编码,再在后台使用解码。
- encodeURI()定义和用法
encodeURI() 函数可把字符串作为 URI 进行编码。
var xmlhttp = new XMLHttpRequest();
var DataGet;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
DataGet = xmlhttp.responseText;
}
}
//此处使用encodeURI()函数
content = encodeURI(encodeURI(content));
xmlhttp.open("GET", "http://localhost:8080/addData?content=" + content, false);
xmlhttp.send();
然后在后台Servlet中使用URLDecoder进行解码,代码如下:
String content = URLDecoder.decode(req.getParameter("content"), "UTF-8");
这样得到的content就是正常的中文数据。