JQuery异步获取返回值中文乱码的解决方法
作者:bea
用jqgrid异步获取列表值,遇到个问题,服务器端从数据库取到的数据没有出现中文乱码问题(日志打出来是没有乱码的),但是异步传到客户的时候却出现了乱码。 服务器端已经编码过了(UTF-8编码)。开始一直怀疑是客户端的问题,比如客户端和服务器端编码不一致啊,也怀疑是不是jqGrid工具函数中少配了 contentType: "application/x-www-form-urlencoded; charset=utf-8", 等等问题。 结果都不是,纠结了几个小时,后来经过大牛
用jqgrid异步获取列表值,遇到个问题,服务器端从数据库取到的数据没有出现中文乱码问题(日志打出来是没有乱码的),但是异步传到客户的时候却出现了乱码。 服务器端已经编码过了(UTF-8编码)。开始一直怀疑是客户端的问题,比如客户端和服务器端编码不一致啊,也怀疑是不是jqGrid工具函数中少配了 contentType: "application/x-www-form-urlencoded; charset=utf-8", 等等问题。
结果都不是,纠结了几个小时,后来经过大牛的提醒发现,原来代码还是出在服务器端,疏忽了。
@RequestMapping(value = "/searchUserList.form")
@ResponseBody
public void searchUserList(int page, int rows, HttpServletRequest request, HttpServletResponse response) throws IOException{
System.out.println("idcard="+idCard+"
page="+page+"
rows="+rows);
List<User> list = userService.findByIDCard(idCard);
int totalRecord = list.size();
int totalPage = totalRecord%rows == 0 ? totalRecord/rows : (totalRecord/rows+1);
int index = (page-1)*rows;
int pageSize = rows;
String json = "{"total": ""+totalPage+"", "page": ""+page+"", "records": ""+totalRecord+"", "rows": [";
for (int i = index; i < pageSize + index && i<totalRecord; i++) {
User u = list.get(i);
json += "{"id":"" + u.getUserId() + "","userName":""+u.getUserName()+"","idCard":""+
u.getIdCard() +"","userTel":""+u.getUserTel()+"","userSex":""+u.getUserSex()+
"","bankCard":""+u.getBankCard()+"","cardStatus":""+u.getCardSatus()+"","createTime":""+
u.getCreateTime()+""}";
if (i != pageSize + index - 1 && i != totalRecord - 1) {
json += ",";
}
}
json += "]}";
request.setCharacterEncoding("utf-8"); //这里不设置编码会有乱码
response.setContentType("text/html;charset=utf-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter(); //输出中文,这一句一定要放到response.setContentType("text/html;charset=utf-8"), response.setHeader("Cache-Control", "no-cache")后面,否则中文返回到页面是乱码
out.print(json.toString());
out.flush();
out.close();
}
猜你喜欢
您可能感兴趣的文章:
- jQuery中$.click()无效问题分析
- Eclipse配置Javascript开发环境图文教程
- js操作滚动条事件实例
- jQuery调取jSon数据并展示的方法
- jquery通过load获取文件的内容并跳到锚点的方法
- 浅谈Javascript 数组与字典
- javascript 数组操作详解
- jQuery实现流动虚线框的方法
- jquery 设置style:display的方法
- jQuery获取样式中颜色值的方法
- JS实现单行文字不间断向上滚动的方法
- JS清除选择内容的方法
- IE中鼠标经过option触发mouseout的解决方法
- JS判断是否360安全浏览器极速内核的方法
- jQuery中$.each使用详解
- jQuery显示和隐藏 常用的状态判断方法
- 移动设备web开发首选框架:zeptojs介绍
- JSON格式的键盘编码对照表
- js的window.showModalDialog及window.open用法实例分析