通过ajax与定时器相结合,实现页面动态数据更新,常使用于提示信息。
需要注意的是,下面代码示例是从JSP页面摘出来的,直接拷贝不能使用,需要修改哦。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'testAAJAx.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(){
      //页面加载即执行函数
      saveUserInfo();
    }
    
    function saveUserInfo()  
    {  
      //获取接受返回信息层  
      var countdown = document.getElementById("countdown");  
      
      //接收表单的URL地址  
      var url=document.getElementsByTagName("a")[0].href;
      
      var ajax = false;  
      
      //开始初始化XMLHttpRequest对象  
      //除IE5 IE6 以外的浏览器XMLHttpRequest是window的子对象
      if(window.XMLHttpRequest)   
      {   //Mozilla 浏览器  
        ajax = new XMLHttpRequest();  
        if (ajax.overrideMimeType)   
        {   //设置MiME类别  
          ajax.overrideMimeType("text/xml");  
        }  
      }  
      //IE5 IE6是以ActiveXObject的方式引入XMLHttpRequest的 
      else if (window.ActiveXObject)   
      {   // 新版本IE浏览器  
        try   
        {  
          ajax = new ActiveXObject("Msxml2.XMLHTTP");  
        }   
        catch (e)   
        {  //兼容老版本浏览器
          try   
          {  
            ajax = new ActiveXObject("Microsoft.XMLHTTP");  
          }   
          catch (e) {
            alert(e.message);
          }  
        }  
      }  
      if (!ajax)   
      {   // 异常,创建对象实例失败  
        window.alert("不能创建XMLHttpRequest对象实例.");  
        return false;  
      }  
              
      //通过GET方式打开连接  
      ajax.open("GET", url, true);  
      
      //定义传输的文件HTTP头信息  ,POST方式下使用
      //ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");  
      
      //发送POST数据  
      ajax.send(null);  
      
      //获取执行状态  
      ajax.onreadystatechange = function(){   
        //如果执行状态成功,那么就把返回信息写到指定的层里  
        if (ajax.readyState == 4 && ajax.status == 200)   
        {   
          countdown.innerHTML += ajax.responseText+"<br/><br/>";   
        }   
      }
      
      /* 等待五秒后再次请求数据 */
      window.setTimeout("saveUserInfo()", 5000);  
    }     
  </script>
  </head>
  
  <body>
    <a href="helloajax.txt">helloajax.txt</a>
    <div id="countdown"></div>
  
  </body>
</html>其实核心思想是下面代码:
function test(){
  window.setTimeout("test()", 5000);  
}                
                










