ajax接收服务端数据中文显示为?的解决办法
ajax响应中文乱码问题及解决方法源码及现象使用ajax函数调用controller后返回的json字符串被页面接收后中文显示为问号。 设置了tomcat,jsp页面,controller,web.xml,ajax等的编码格式都不管用。 后发现浏览器接收返回的数据的格式为ISO-8859-1,怎么也设置不了其他的格式。 现象图: 其源码如下 Jsp+ajax functionajaxwork(user_account,password,validCode){ $.ajax({ url:"check", type:"get", contentType: "application/json;charset=UTF-8", dataType:'text', data:{ "user_account":user_account, "password":password, "validCode":validCode }, beforeSend:function(){ }, success:function(data){ vardataObj = eval("("+data+")"); if(dataObj.success){ alert("登陆成功"); window.location.href="${pageContext.request.contextPath}/index.jsp"; }elseif(dataObj.element=="validCode"){ addClass("vcode_A","vcode_B",dataObj.message); $("#div3").addClass("has-error redLight"); ; }else{ addClass("pwd_A",255)">"pwd_B",dataObj.message); } changeCode(); } }); Controller @RequestMapping(value="/check") @ResponseBody publicJson loginByTaxNum( @RequestParam(value="user_account",required=true) String user_account, "password",85)">true) String password,255)">"validCode",85)">true) String validCode, HttpSession session, HttpServletResponse response, HttpServletRequest request) throwsUnsupportedEncodingException{ //获取验证图片的验证码 Json json = newJson(); String kaptcha = (String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); if(kaptcha.equalsIgnoreCase(validCode)){ //对比验证图片的验证码和用户输入的验证码 User user = null; try{ user = userService.getUserbyName(user_account); if(user==null) { return“{message:‘账户不存在’}”; } String password2 = user.getPassWord(); if(!password.equals(password2)){ 密码错误’}”; } } catch(Exception e) { e.printStackTrace(); } session.setAttribute("user",user); json.setSuccess(true); return“{success:’}”; } json.setElement("validCode"); json.setMessage("验证码错误"); return“{element:validCode’,message:验证码错误’}”; } } 解决方法1,原因@responseBody注解自动将对象转换成json字符串,所以只返回对象就行,不用返回字符串(至于原因还不太清楚,求知道的大神指点)。 2,解决方法,将需要返回的信息封装到对象中(这里本人设置了一个Json类,将数据封装到里面),修改代码如下(jsp的代码不变,只修改controller的代码) //对比验证图片的验证码和用户输入的验证码 User user = null) { json.setMessage("账户不存在"); returnjson; } String password2 = user.getPassWord(); if(!password.equals(password2)){ json.setMessage("密码错误"); returnjson; } } returnjson; } json.setElement(returnjson; } } 修改后页面显示正常 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |