用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+"\n page="+page+"\n 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(); }