ajax返回值为中文时乱码解决方法

/** 
  * 使用ajax检查用户是否存在 
  */ 
 public void checkUser()
 {  
     try
     {  
         System.out.println("userName="+user.getUserName());  
         HttpServletResponse response=ServletActionContext.getResponse();  
         response.setContentType("text/xml;charset=utf-8");  
         response.setHeader("Cache-Control", "no-cache");  
         PrintWriter pw=response.getWriter(); //输出中文,这一句一定要放到response.setContentType("text/xml;charset=utf-8"),  response.setHeader("Cache-Control", "no-cache")后面,否则中文返回到页面是乱码  
       
         if(existUser.contains(user.getUserName()))  
         {  
             pw.print("存在");  
         }
         else
         {  
            pw.print("不存在");  
         }  
        pw.close();  
     }catch(IOException e)
     {  
         e.printStackTrace();  
     }  
 } 

 

/**
  * The doGet method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to get.
  *
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  */
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  //response.setContentType("text/html");
  response.setContentType("text/xml;charset=utf-8");  
  response.setHeader("Cache-Control", "no-cache");
  PrintWriter out = response.getWriter();
  
  String userNames = request.getParameter("userName");
  String userName = new String(userNames.getBytes("ISO8859-1"),"GB2312");
  System.out.println("传过来的用户名:"+userName);
  
  //调用查询方法
  StringBuffer str = new StringBuffer();
  String strs = "";
  List<Map<String,Object>> list = UserGroupService.getAllUserByUserName(userNames);
  if(list!=null && list.size()>0)
  {
   for(Map<String,Object> map:list)
   {
    String name = map.get("username").toString();
    System.out.println("从数据库中取出来的用户名:"+name);
    Integer uid = Integer.parseInt(map.get("uid").toString());
    System.out.println("从数据库中取出来的用户Id:"+uid);
    
    str.append(name);
    str.append("|");
    str.append(uid);
    str.append(",");
   }
   strs = str.toString().substring(0,str.toString().length()-1);
  }
  else
  {
   strs = "0";
  }
  out.print(strs);
 }

 /**
  * The doPost method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to post.
  *
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  doGet(request,response);
 }

你可能感兴趣的:(ajax返回值为中文时乱码解决方法)