日期:2014-05-16  浏览次数:20805 次

ajax中url中文乱码问题
在写web 页面基本上是用ajax写的 
是ajax+servlet

xmlhttp.send();
xmlhttp.onreadyStatechange = function(){
if(xmlhttp.readyState==4){
if(xmlhttp.status==200){
//alert("响应完毕");
var tb = document.getElementById("tb");
for(var i=0;i<tb.rows.length;i++){
tb.removeChild(tb.childNodes[i]);
}
var str = xmlhttp.responseText.split("|&|");
var ids = str[0].split("|#|");
var names = str[1].split("|#|");
var sexs = str[2].split("|#|");
var hobbys = str[3].split("|#|");
var newTR = tb.insertRow();
var cell1 = newTR.insertCell();
var cell2 = newTR.insertCell();
var cell3 = newTR.insertCell();
var cell4 = newTR.insertCell();
var cell5 = newTR.insertCell();
cell1.innerHTML = "id";
cell2.innerHTML = "name";
cell3.innerHTML = "sex";
cell4.innerHTML = "hobby";
cell5.innerHTML = "操作";
for(var i=0;i<ids.length-1;i++){
var newTRs = tb.insertRow();
var cell1s = newTRs.insertCell();
var cell2s = newTRs.insertCell();
var cell3s = newTRs.insertCell();
var cell4s = newTRs.insertCell();
var cell5s = newTRs.insertCell();
cell1s.innerHTML = ids[i];
cell2s.innerHTML = "<a href='#' onclick='selectInfo("+ids[i]+")'>"+names[i]+"</a>";
cell3s.innerHTML = sexs[i];
cell4s.innerHTML = hobbys[i];
cell5s.innerHTML = "<a href='#' onclick='deleteRow("+ids[i]+","+this+")'>删除</a>"

}
}
}
}
}
这是我写的js传参提示
UserServlet?id=40&name=张三&sex=1&hobby=篮球&flag=1
在servlet里转换不过来了,都是乱码!配过滤器也不行,手动的也不可以。

int id = Integer.parseInt(request.getParameter("id").toString());
String name = new String(request.getParameter("name").getBytes("utf-8"), "iso8859-1");
/*String name = Escape.unescape(request.getParameter("name")).trim();*/
System.out.println(name);
int sex = Integer.parseInt(request.getParameter("sex").toString());
String hobby = new String(request.getParameter("hobby").getBytes("utf-8"), "iso8859-1");
输出的结果是乱码!
求解决 最好可以给稍微详细点的。

------解决方案--------------------
都用过滤器解决算了。
找个过滤器吧

还有传递url参数时候 java.net.URLEndoder.encode
------解决方案--------------------
JScript code
var url = "UserServlet?id=40&name=张三&sex=1&hobby=篮球&flag=1";
url = encodeURI(url);
url = encodeURI(url);//编码2次

------解决方案--------------------
补充一下:拉了一点东西String str = new String(request.getParameter(""),"ISO-8859-1");
-------》String str = new String(request.getParameter("").getBytes(""),"ISO-8859-1");