AJAX处理汉字乱码的问题

  JSP中乱码产生的原因是web容器(Tomcat)默认使用ISO-8859-1进行编码的,而我们可能使用的是UTF-8,GBK,GB2312等编码方式进行jsp编写的,因此需要一个转换器进行转换或者修改默认编码方式,这里我主要用转换器+过滤器完成自动转换功能.

   客户端脚本文件:

View Code
/*
 * name:getTransport
 * create XMLHttpRequest
 */
 var xmlhttp=null;
 function getHttpRequest() 
 {
   try
   {
    xmlhttp=new ActiveXObject('Msxml2.XMLHTTP');
   }
   catch(e)
   {
        try
          {
                xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
          }
          catch(e1)
          {
              xmlhttp=new XMLHttpRequest();
          }
       
   }
 }
 

 
function httpGet(url,method,data)
{
 if(xmlhttp==null)
 getHttpRequest();
 xmlhttp.open(method,url +"?"+data,true);//有回调函数时为true,没有时false
 xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
 xmlhttp.setRequestHeader("Content-Length",data.length);
 xmlhttp.onreadystatechange=getCallback;
 xmlhttp.send (null);
}

function getCallback()
{
     if(xmlhttp.readyState==4)
     {  
       if(xmlhttp.status==200)
       {            
           var xmlDoc=xmlhttp.responseText;
           data=eval(xmlDoc);
           var tableFormat="<table rules='all' ><tr><td class='tablehead'>编号</td><td class='tablehead'>姓名</td><td class='tablehead'>性别</td><td class='tablehead'>电话</td><td class='tablehead'>地址</td><td class='tablehead'>星座</td><td class='tablehead' colspan='2'>操作</td></tr>";
           
           for(var key in data)
           {
               tableFormat+="<tr><td>"+data[key].id+"</td><td>"+data[key].name+"</td><td>"+data[key].sex+"</td><td>"+data[key].phone+"</td><td>"+data[key].address+"</td><td>"
               +data[key].constellation+"</td><td><a target='"+data[key].id+"' title='修改' onclick='openedit(this)'><img src='img/edit.jpg'></a></td><td><a target='"+data[key].id+"' title='删除' onclick='opendel(this)'><img src='img/del.jpg' ></a></td></tr>";
           }
           tableFormat+="</table>";
           document.getElementById("showout").innerHTML=tableFormat;
       }
       else
       {
           document.getElementById("showout").innerHTML="AJAX Server error,code:"+xmlhttp.status+"!"; 
       }      
     }
}

function httpPut(url, method, data)
{    
    if(xmlhttp==null)
     getHttpRequest();
     xmlhttp.open(method,url,true);
     xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
     xmlhttp.setRequestHeader("Content-Length", data.length);
     xmlhttp.onreadystatechange=putCallback;
     xmlhttp.send(data);
}
 
function putCallback()
{    
     var panel=document.getElementById("showsuccess");
     if (xmlhttp.readyState==4) 
     {  
         if(xmlhttp.Status >=400 && xmlhttp.Status <=599)
           panel.innerHTML="Error Occurred : "& xmlhttp.Status & "-" & xmlhttp.statusText;
         else
           {
             panel.innerHTML=xmlhttp.responseText;
             httpGet("myServlet", "GET", "name="+"获得数据");
           }
         
         setTimeout(hideinfo,1000);
     }
}

function  httpPost(url, method, data)
{
    if(xmlhttp==null)
     getHttpRequest();
     xmlhttp.open(method,url,true);
     xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
     xmlhttp.setRequestHeader("Content-Length",data.length);
     xmlhttp.onreadystatechange=postCallback;
     xmlhttp.send(data);                                                                                       
}

function postCallback()
{    
     var panel=document.getElementById("showsuccess");
     if(xmlhttp.readyState==4)
     {  
       if(xmlhttp.status==200)
       {
           if(xmlhttp.Status >=400 && xmlhttp.Status <=599)
             panel.innerHTML="Error Occurred : "& xmlhttp.Status & "-" & xmlhttp.statusText;
           else
             {
               panel.innerHTML=xmlhttp.responseText; 
               httpGet("myServlet", "GET", "name="+"获得数据");
             }
           setTimeout(hideinfo,1000);
       }
      }
}

function httpDelete(url, method, data)
{    
    if(xmlhttp==null)
     getHttpRequest();
     xmlhttp.open(method,url+"?"+data,true);
     xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
     xmlhttp.setRequestHeader("Content-Length", data.length);
     xmlhttp.onreadystatechange=deleteCallback;
     xmlhttp.send(null); 
}

function deleteCallback()
{
     if (xmlhttp.readyState==4) 
     {   
         if(xmlhttp.Status >=400 && xmlhttp.Status <=599)
             document.getElementById("showsuccess").innerHTML="Error Occurred : "& xmlhttp.Status & "-" & xmlhttp.statusText;
         else
         {
             document.getElementById("showsuccess").innerHTML=xmlhttp.responseText;    
             httpGet("myServlet", "GET", "name="+"获得数据");
         }
         setTimeout(hideinfo,1000);
     }    
}

function getAjaxJson()
{   
  httpGet("myServlet", "GET", "name="+"获得数据"); 
}

function addAjaxJson()
{
 var panel=document.getElementById("addpanel");
 document.getElementById("title").innerHTML="增加学生信息选项卡";
 panel.style.top='50px';
 panel.style.left='200px';
 panel.style.display='block';
 document.getElementById("addedit").value="提交";
 flag=true;
}

function closepanel()
{   
  document.getElementById("addpanel").style.display='none';
}

function addrecord()
{   
    var panel=document.getElementById("showsuccess");
    var s= new Object();
    s.Id=id;
    s.Name=document.getElementById("name").value;
    s.Sex=document.getElementById("sex").value;
    s.Phone=document.getElementById("tel").value;
    s.Address=document.getElementById("address").value;
    s.Constellation=document.getElementById("star").value;
    if(s.Name=="")
    {
        panel.innerHTML="学生姓名不能为空";
        setTimeout(hideinfo,1000);
        return;
    }
    if(s.Sex=="")
    {
        panel.innerHTML="学生性别不能为空";
        setTimeout(hideinfo,1000);
        return;
    }
    
    if(s.Phone=="")
    {
        panel.innerHTML="学生电话不能为空";
        setTimeout(hideinfo,1000);
        return;
    }
    if(s.Address=="")
    {
        panel.innerHTML="学生家庭不能为空";
        setTimeout(hideinfo,1000);
        return;
    }
    if(s.Constellation=="")
    {
        panel.innerHTML="学生星座不能为空";
        setTimeout(hideinfo,1000);
        return;
    }
    var data= JSON.stringify(s);
    if(flag==true) 
    {
      httpPut("myServlet","PUT",data);
    }
    else
    {
      httpPost("myServlet","POST",data);
    }
}

function openedit(obj)
{
     var panel=document.getElementById("addpanel");
     document.getElementById("title").innerHTML="更新学生信息选项卡";
     panel.style.top='50px';
     panel.style.left='200px';
     panel.style.display='block';
     document.getElementById("addedit").value="保存";
     for(var key in data)
     {
        if(data[key].id==obj.target)
        {   
            id=data[key].id;
            document.getElementById("name").value=data[key].name;
            document.getElementById("sex").value=data[key].sex;
            document.getElementById("tel").value=data[key].phone;
            document.getElementById("address").value=data[key].address;
            document.getElementById("star").value=data[key].constellation;
            break;
        }
     }     
     flag=false;
}

function opendel(obj)
{    
  var mid=null;
  for(var key in data)
  {
   if(data[key].id==obj.target)
   {  
     mid=data[key].id;
     break;
   }
  }    
 if(confirm("你确定要删除数据吗?"))
 httpDelete("myServlet","DELETE","id="+mid);
}

function hideinfo()
{
    document.getElementById("showsuccess").innerHTML='';    
}

      首先,项目中所有的源文件(.class,*js,*.css)的编码方式改为UTF-8。 

   1.  AJAX GET和DELETE方法中文乱码处理.  

  配置tomcat的server.xml 的<Connector>的URIEncoding="UTF-8",它只对拼接在url后面的参数有作用,保证它是采用指定的编码。

   参照http://www.blogjava.net/leekiang/archive/2007/10/17/153685.html

   <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/> 

    在Servlet的doGet()和doDelete()方法中直接得到传递的参数.

    String name=request.getParameter("name").toString();   

   2. AJAX POST和PUT方法中使用过滤器(所有编码方式为过滤器中设置的编码方式)

   继承过滤器类实现它的方法的EncodeFilter.java:

View Code
package commons;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class EncodeFilter implements Filter {
    private String encoding = "";

    public void destroy() {
        // TODO Auto-generated method stub
    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding(encoding);
        chain.doFilter(request, response);
    }

    public void init(FilterConfig config) throws ServletException {
        // TODO Auto-generated method stub
        encoding = config.getInitParameter("encoding");
        //get encoding from web.xml
    }
}

  配置工程的web.xml文件,加入<filter> </filter>和<filter-mapping>  </filter-mapping>的相关配置  

  注意:<filter-class>commons.EncodeFilter</filter-class>中的包名.类名,与你实现的过滤器类要一致。

View Code
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>jsonexample</display-name>
 <servlet>
        <servlet-name>myServlet</servlet-name>
        <servlet-class>com.myServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>myServlet</servlet-name>
    <url-pattern>/myServlet</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encoding</filter-name>
<filter-class>commons.EncodeFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>  
</web-app>

  在Servlet的doPut()和doPost()方法中直接获取传递的数据即可。

   BufferedReader sis = request.getReader(); 
   String data=sis.readLine().toString();

   除了过滤器方法,还可以在Servlet的doPut()和doPost()方法中用

request.setCharacterEncoding("UTF-8")的作用是设置对客户端请求进行重新编码的编码,此方法对doGet()和doDelete()方法无效。

这种存在一个问题就是每次doPut()和doPost()方法中都要设置请求的编码,所以一劳永逸的方法还是设置过滤器。

 这样就完美解决了AJAX开发乱码的问题,如有问题,请留言。

posted @ 2013-04-12 20:55  方子格  阅读(500)  评论(1编辑  收藏  举报