日期:2014-05-16 浏览次数:20313 次
我有一段ajax代码(典型的ajax客户端代码),需要在url中传递中文参数:
?
function show() { var desc = document.search.desc.value; //desc的值有可能是中文 var url = "deal.jsp?desc=" + desc; // alert(url); if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); } req.open("post", url, true); req.onreadystatechange = callback; req.send(null); } function callback() { if (req.readyState == 4) { if (req.status == 200) { // deal with the response text // alert(req.responseText); eval(req.responseText); } else { // 如果失败,刷新页面 alert(req.status + "\r\n" +req.responseText); window.location = location; } } }
?
?在服务器端采用如下方式处理乱码:
?
desc = new String(desc.getBytes("ISO-8859-1"), "UTF-8"); // 会出现乱码
?
?结果是:(1)网站部署在windows服务器上时,Chrome和FireFox会出现乱码,IE正常;
(2)网站部署在linux服务器上时,IE会出现乱码,Chrome和FireFox正常。
No.1 在Javascript客户端,对中文参数进行两次encodeURI操作:
?
desc = encodeURI(desc); desc = encodeURI(desc); // 两次encodeURI转换
?
?No.2 在服务器端,再进行解码:
?
desc = java.net.URIDecoder.decode(desc, "UTF-8");
?经过这两步,无论window还是Linux做服务器,无论IE,Chrome还是FireFox,均无乱码,问题解决。
?
response.setContentType("text/xml;charset=utf-8");// (1)一定要在(2)的前面,不然会乱码 response.setCharacterEncoding("UTF-8"); // (2) response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1 response.setHeader("Pragma", "no-cache"); // HTTP 1.0 response.setDateHeader("Expires", 0); // prevents catching at proxy server