工作中,因为碰到ajax乱码问题,终于想出一个够绝的办法,
问题是:从客户端用ajax对象传数据到服务器段出现乱码,服务端的程序有过滤器,会自己进行一些处理,我也不知道怎么处理的,总之汉字就是显示乱码,
应对办法,javascript有一个encodeURIComponent
方法,java也有对应方法在java.net包中
对要传送的参数编码两次,在java中解码一次就OK,此办法只针对用正常办法解决不了的问题,属于歪招。
客户端代码:
function test11(){
createXMLHttp();
xmlHttp.onreadystatechange = handleState;
var han = "汉字 s";
var url = "/portal/event/fwczh/testAjax";
var han3 = encodeURIComponent(encodeURIComponent(han)); //这句话重要
url += "?a="+han3;
xmlHttp.open("GET",url,true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttp.send(null);
}
var xmlHttp;
function createXMLHttp(){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
function handleState(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
alert(xmlHttp.responseText);
}
}
}
服务端代码:
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Cache-Control", "no-store");
response.setDateHeader("Expires", 0);
response.setHeader("Pragma", "no-cache");
//out.clear();
String sss = request.getParameter("a");
System.out.print("转变前:"+sss);
String b = URLDecoder.decode(sss,"UTF-8");//这句话重要
System.out.print("转变后:"+b);
out.print(b);
out.close();