首页 > 代码库 > 4.4 创建自动刷新页面

4.4 创建自动刷新页面

<1>使用Ajax,用户就可以不必反复点击刷新按钮,而实现网页内容的自动刷新
<2>例程采用单击按钮后开始执行,实际中一般以onload事件代替
<3>setTimeout方法,允许以固定的时间间隔(单位为毫秒)执行给定的方法
<4>createRow()方法使用DOM动态创建内容;refreshTime()用于刷新定时器的值

页面代码:

技术分享
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Insert title here</title>
  <script type="text/javascript">
  var xmlHttp;

  alert("dasd");

  function createXMLHttpRequest(){
    if(window.ActiveXObject){
      xmlHttp = new ActiveXObject();
    }
    else if(window.XMLHttpRequest){
      xmlHttp = new XMLHttpRequest();
    }
  }
  
  //第一次请求获取全部数据
  function doStart(){
    
    createXMLHttpRequest();
    var url = "DynamicUpdateServlet?task=reset";
    xmlHttp.open("GET", url, true);
    
    xmlHttp.onreadystatechange = startCallback;
    xmlHttp.send(null);
  }

  function startCallback(){
    if(xmlHttp.readyState == 4){
      if(xmlHttp.status == 200){
        //每5秒查询是否有新数据
        setTimeout("pollServer()", 5000);
        //页面动态变化刷新时间
        refreshTime();
      }
    }
  }

  function pollServer(){
    createXMLHttpRequest();
    var url = "DynamicUpdateServlet?task=foo";
    xmlHttp.open("GET", url, true);
    xmlHttp.onreadystatechange = pollCallback;
    xmlHttp.send(null);
  }

  function refreshTime(){
    var time_span = document.getElementById("time");
    var time_val = time_span.innerHTML;
    var int_val = parseInt(time_val);
    var new_int_val = int_val-1;

    if(new_int_val > -1){
      //每秒执行一次刷新
      setTimeout("refreshTime()", 1000);
      time_span.innerHTML = new_int_val;
    }else{
      time_span.innerHTML = 5;
    }
  }

  function pollCallback(){
    if(xmlHttp.readyState == 4){
      if(xmlHttp.status == 200){
        var message = xmlHttp.responseXML.getElementsByTagName("message")[0].firstChild.data;
        if(message != "done"){
          var new_row = createRow(message);
          var table = document.getElementById("dynamicUpdateArea");
          var table_body = table.getElementsByTagName("tbody").item(0);
          var first_row = table_body.getElementsByTagName("tr").item(1);
          table_body.insertBefore(new_row, first_row);
        }//done
        //5秒后重新查询是否有新的内容
        setTimeout("pollServer()", 5000);
        refreshTime();
      }//200
    }//4
  }

  function createRow(message){
    var row = document.createElement("tr");
    var cell = document.createElement("td");
    var cell_data = document.createTextNode(message);
    cell.appendChild(cell_data);
    row.appendChild(cell);
    return row;
  }

  </script>
</head>
<body>
  <h1>Ajax Dynamic Update Example</h1>
  
  This Page will automatically update itself:
    <input type="button" value="Launch" id="go" onclick="doStart();"/>
  <p>
  Page will refresh in <span id="time">5</span> seconds.
  </p>

  <table id="dynamicUpdateArea" align="left">
    <tbody>
      <tr id="row"><td></td></tr>
    </tbody>
  </table>
  

</body>
</html>
View Code

后台代码:

技术分享
package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/DynamicUpdateServlet")
public class DynamicUpdateServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    private int counter = 1;
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doGet");
        String res = "";
        String task = request.getParameter("task");
        String message = "nothing";
        
        if(task.equals("reset")){
            counter = 1;
        }else{
            switch (counter) {
            case 1:message = "明月几时有"; break;
            case 2:message = "把酒问青天"; break;
            case 3:message = "不知天上宫阙"; break;
            case 4:message = "我欲乘风归去"; break;
            case 5:message = "又恐琼楼玉宇"; break;
            case 6:message = "高处不胜寒"; break;
            case 7:message = "起舞弄清影"; break;
            case 8:message = "何似在人间"; break;
            default: message="done"; break;
            }
            ++counter;
        }
        res = "<message>"+message+"</message>";
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/xml; charset=utf-8");
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();
        out.println("<response>");
        out.println(res);
        out.println("</response>");
        out.close();
    }
}
View Code

 

4.4 创建自动刷新页面