用jqgrid異步獲取列表值,遇到個問題,服務器端從數據庫取到的數據沒有出現中文亂碼問題(日志打出來是沒有亂碼的),但是異步傳到客戶的時候卻出現了亂碼。 服務器端已經編碼過了(UTF-8編碼)。開始一直懷疑是客戶端的問題,比如客戶端和服務器端編碼不一致啊,也懷疑是不是jqGrid工具函數中少配了 contentType: "application/x-www-form-urlencoded; charset=utf-8", 等等問題。
結果都不是,糾結了幾個小時,后來經過大牛的提醒發現,原來代碼還是出在服務器端,疏忽了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
@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(); } |