一、Post请求(get请求同理)

a)         Javascript

       var httpRequest;

        //创建异步请求对象

        function createXMLHttpRequest(){

             if(window.XMLHttpRequest){

                 httpRequest=new XMLHttpRequest();

            }else if(window.ActiveXObject){

                 try{

                 httpRequest=new ActiveXObject("Msxml2.XMLHTTP");

                 }catch(e){

                try{

httpRequest=newActiveXObject("Microsoft.XMLHTTP");

                    }catch(e){}

                }

            }

        }

  

    function getData(){

        //创建异步请求对象

       createXMLHttpRequest();

       //设置请求的回调函数

       httpRequest.onreadystatechange=callBack;

       //创建新的http请求,指定请求的方法,url,以及验证信息  

        //httpRequest.open("GET","/TestAJAX/ajax.jsp?date="+new Date(),true);

        httpRequest.open("POST","/TestAJAX/ajax.do",true);

       //Post请求必须进行setRequestHeader以下2个参数

httpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");

httpRequest.setRequestHeader("Content-type","text/html;charset=utf-8");

        //发送请求至服务器,并接收回应

        var post = "date="+"今天"+new Date();

        post=encodeURI(post);

       post=encodeURI(post);

//最重要的部分,两次调用encodeURI ,就是编码两次,此动作是为了防止对中文参数的乱码。若在你的项目中不存在一个编码过滤器(一般为UTF-8),你必须将你的中文参数进行2encoding,且服务端获取参数后还需将其decoding;若你项目中存在一个编码过滤器,则你需要在此处进行一次encoding,而服务端不需要进行decoding

       httpRequest.send(post);

       //httpRequest.send(null);

   }

   //回调函数

   function callBack(){

     //如果请求数据接收完毕

      if(httpRequest.readyState==4&&httpRequest.status==200){

      //将返回的请求文本(这里实际上就是data.jsp)写入指定的DIV

      alert(httpRequest.responseText);

           document.getElementById("dataDiv").innerHTML=httpRequest.responseText;

     }

   }

  

b)         Jquey

function loadData(){

        alert("loadData");

       var post = "今天"+new Date();

        post=encodeURI(post);

//重要部分,此处需要将中文参数进行encoding一次而不是二次。若你项目中存在编码过滤器,则不需要进行编码,若不存在需要进行编码,并在服务端进行解码。

       $.post("/TestAJAX/ajax.do",{date:post},function(result){

           alert(result);

           $("#jqueryDataDiv").html(result);

       });

}

附:服务端简易代码

String date = request.getParameter("date")==null?"":request.getParameter("date").toString();

    date = URLDecoder.decode(date,"UTF-8");

二、关于中文参数乱码的解决方案

a)         给项目添加编码过滤器,若你使用jquery则客户端和服务不再需要进行编码处理,若是使用基础ajax那还需要进行对客户端进行一次编码。

b)         不添加过滤器的情况,不管是那种方式都需要对参数进行编码和解码操作,详细请看上面代码。

c)         其它解决方式,如果你对其它的解决方案感兴趣请去baidu.com或者google.com.hk.个人认为熟悉运用一种方式就ok了。