当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JQuery异步获取返回值中文乱码的解决方法

JQuery异步获取返回值中文乱码的解决方法

2019年03月31日  | 移动技术网IT编程  | 我要评论

jquery异步获取返回值中文乱码的解决方法,用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();
  }


如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网