ajax-POST

来源:互联网 发布:汪清县淘宝特产 编辑:程序博客网 时间:2024/06/05 09:16

要求同GET

一.servlet

 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException
 {
  String num1 = request.getParameter("num1");
  String num2 = request.getParameter("num2");
  
  response.setHeader("progma","no-cache");
  response.setHeader("Cache-control","no-cache");
  String num3 = String.valueOf(Integer.valueOf(num1)+Integer.valueOf(num2));
  
  
  PrintWriter out = response.getWriter();
  out.println(num3);
  out.flush();
  
 }

二.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
        <title>My JSP 'ajaxPOST.jsp' starting page</title>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 <script type="text/javascript">
  window.onload = function()
  {
   var ajaxButton = document.getElementById("ajaxButton");
   
   // var num1 = document.getElementsByName("num1")[0].value;//注意页面刚加载时可能会获得不到value值哦
   // var num2 = document.getElementsByName("num2")[0].value;
   
  
   
   //alert("num1="+num1+",num2="+num2);
   var xmlHttpRequest = null;//初始化xmlHttpRequest对象
   ajaxButton.onclick = function()
   {
    if(window.ActiveXObject)//IE
    {
     xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
     
    }
    else if(window.XMLHttpRequest)//其它浏览器
    {
     xmlHttpRequest = new XMLHttpRequest();
    }
    
    if(null != xmlHttpRequest)
    {
     var num1 = document.getElementsByName("num1")[0].value;
     var num2 = document.getElementsByName("num2")[0].value;
     //通过POST方式打开连接
     xmlHttpRequest.open("POST","AjaxPOST",true);
     //回调函数
     xmlHttpRequest.onreadystatechange = function()
     {
      if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)
      {
       document.getElementById("ajaxDiv").innerHTML = xmlHttpRequest.responseText;
      }
     }
     //表单提交的编码方式,
     xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
     // alert("num1="+num1+"&num2="+num2);
     xmlHttpRequest.send("num1="+num1+"&num2="+num2);
    
    }
    
   }
  } 
 </script>
  </head>
  <body>
  <form action="AjaxPOST" method="post">
   <input type="button" value="send to server(post)" id="ajaxButton"><br>
   <input type="text" name="num1" id="num1"><br>
   <input type="text" name="num2" id="num2" ><br>
   <div id="ajaxDiv"></div>
  </form>
  </body>
</html>