Home  >  Article  >  Web Front-end  >  JQuery asynchronously obtains the solution to the Chinese garbled return value_jquery

JQuery asynchronously obtains the solution to the Chinese garbled return value_jquery

WBOY
WBOYOriginal
2016-05-16 16:17:15994browse

Using jqgrid to asynchronously obtain list values, I encountered a problem. The data obtained by the server from the database did not have Chinese garbled characters (the logs were typed without garbled characters), but when it was asynchronously transmitted to the client, garbled characters appeared. The server side has been encoded (UTF-8 encoding). At first, I always suspected that it was a problem with the client. For example, the coding between the client and the server was inconsistent. I also suspected that the jqGrid tool function was missing contentType: "application/x-www-form-urlencoded; charset=utf-8", etc. etc. questions.

The result was neither, and I struggled for several hours. Later, after being reminded by Daniel, I discovered that the original code was still on the server side, and it was an oversight.

@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 &#63; 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();
  }
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn