xmlHttpRequest的post方法

来源:互联网 发布:简明python教程 从哪买 编辑:程序博客网 时间:2024/05/22 06:38

js文件:

/*

 * ajax建立和服务器的连接,接收服务器的请求,处理服务器返回的数据
 *         *创建XMLHttpRequest对象
 *         打开和服务器的连接
 *         发送数据
 *         接收服务器端的响应
 */

function ajaxFunction(){
    var xmlHttp;
    try{
        xmlHttp=new XMLHttpRequest();
    } catch(e){
        try{
            xmlHttp=new ActiveXObject("MSXML2.XMLHTTP");
        }catch(e){
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}

window.onload=function(){
    /*
     * <input type="button" name="ok" id="ok" value="测试服务器连接" />
     */    
    //获取xmlHttpRequest对象
    xmlhttp=ajaxFunction();
    
    document.getElementById("ok").onclick=function(){
        
        //接收服务器端的数据
        xmlhttp.onreadystatechange=function(){
            if (xmlhttp.readyState==4){    
                //200服务器处理成功    304文件没有被找到    
                if(xmlhttp.status==200 || xmlhttp.status==304){
                    var date=xmlhttp.responseText;
                    alert(date);
                }
            }
        }
        
        
        //打开和服务器的连接
        /*
         * XMLHttpRequest.open(bstrMethod, bstrUrl, varAsync
         *         * bstrMethod: get post
         *         * bstrUrl 代表请求的路径
         *         * varAsync 表示是否要异步传输
         */
        
        
        xmlhttp.open("post","/jstest/TestServlet?timeStamp="+new Date().getTime(), true);
        
        //和get方式不同的(该方法必须放在open之后)        表示符合url编码                    还有一个是传输二进制的
        xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        
        //发送数据
        //若选用get方式,则不会发送任何数据,给send方法传递null即可
        xmlhttp.send();
        
        
    };

};


jsp文件:

<script language="JavaScript" src="./jquery.js"> </script>
<script language="JavaScript" src="./jquery-1.9.0.min.js"></script>
  </head>
          <script type="text/javascript" src="testPost/test.js"></script>
  <body>
          <form action="" enctype="application/x-www-form-urlencoded">
              <input type="button" name="ok" id="ok" value="post测试服务器连接">
          </form>    
  </body>

servlet文件:

public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print("post connect server ok!");
        System.out.println("post");
    }


0 0
原创粉丝点击