
使用ajax做数据传输时,中文很多时候会在服务器以乱码方式显示。下面总结了几条解决乱码的方法,供大家参考。
1、客户端采用POST提交(尽量采用这种方式,POST本身是用于数据传输的,可以传输大文本)
xmlHttp.open("POST","select",true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttp.send("contry="+obj.innerHTML);
服务器端设置请求编码集
request.setCharacterEncoding("utf-8");
2、客户端采用GET提交
a方案:
客户端代码:
//将中文重新编码
var str = encodeURI(obj.innerHTML);
xmlHttp.onreadystatechange = press;
xmlHttp.open("GET","select?contry="+str,true);
xmlHttp.send(null);
服务器代码:
byte[] by = contry.getBytes("ISO8859-1");
String str = new String(by,"utf-8");
b方案:
客户端代码:
//将中文重新编码
var str = encodeURI(encodeURI(obj.innerHTML));
xmlHttp.onreadystatechange = press;
xmlHttp.open("GET","select?contry="+str,true);
xmlHttp.send(null);
服务器代码:
String str = URLDecoder.decode(contry, "utf-8")