ajax的一个基本例子

一.创建servlet类

doGet中的方法

 PrintWriter out = response.getWriter();
  out.println("hello world ,this is my first ajax");
  out.flush();

二.编写页面jsp

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
 <script type="text/javascript">
  window.onload = function()
  {
   var myAjaxButton = document.getElementById("ajaxButton");
   myAjaxButton.onclick = function()
   {
    //声明一个空对象,用来接收XMLHttpRequest
    var xmlHttpRequest = null;
    if(window.ActiveXObject)//IE
    {
     xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if(window.XMLHttpRequest)
    {
     xmlHttpRequest = new XMLHttpRequest();
    }
    
    if(null != xmlHttpRequest)
    {
     //准备建立一个连接
     xmlHttpRequest.open("GET","MyAjaxServlet",true);
     //关联ajax的回调函数
     xmlHttpRequest.onreadystatechange = function()
     {
      if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)
      {
       //处理响应
       document.getElementById("ajaxDiv").innerHTML = xmlHttpRequest.responseText;
      }
     }
     
         
     //真正向客户端发送数据
     xmlHttpRequest.send(null);
    }
   
     
   }
  
  }
 
 
 </script>
  </head>
 
  <body>
   <form action="AjaxServlet" method="post">
  <input type="button" value="get info from server" id="ajaxButton">
  <div id="ajaxDiv"></div>
 </form>
  </body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值