AJAX 解决传中文乱码问题
1.javascript代码
<script type="text/javascript"> //http://www.w3school.com.cn/ajax/index.asp var xmlHttp; function getCN(obj) { var author = document.forms[0].u367766562624002.value; //中文值 author=encodeURI(author); author=encodeURI(author); //传送的值,2次转码。 try{ // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); }catch (e){ //Internet Explorer try{ xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); }catch (e){ // IE6, IE5 try{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }catch (e){ alert("您的浏览器不支持AJAX!"); return false; } } } xmlHttp.onreadystatechange=function(){ if(xmlHttp.readyState==4 && xmlHttp.status==200){ var result=xmlHttp.responseText; document.forms[0].u367763762460602.value=result; } }; var url = "xzShow.do?show=getcn&uname="+author; xmlHttp.open("POST",url,true); xmlHttp.send(null); } </script>
2.后台java代码
public ActionForward execute(ActionMapping mapping, ActionForm actionform, HttpServletRequest request, HttpServletResponse response, SessionUser sessionuser) throws Exception { response.setContentType("text/html"); response.setCharacterEncoding("GBK"); PrintWriter out = response.getWriter(); String uname=StringUtils.trim(request.getParameter("uname")); uname=URLDecoder.decode(uname,"utf8"); //解码 System.out.println("-----"+uname); if(!uname.equals("")){ out.print("你好"); } out.close(); return null; }