日期:2011-01-25  浏览次数:20470 次

  一个无刷新效果定时自动更新页面的例子(ASP.NET2.0-应用xmlhttp)

  首先在ASP.Net创建两个WebForm页,分别命名为Default1,Default2。下面给出代码清单:

//Default1.aspx

<%@ Page Language="C#" Debug="true" AutoEventWireup="true" CodeFile="Default1.aspx.cs" Inherits="Default1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html Xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
  <title>无标题页</title> 
  <script type="text/javascript">
    var XmlHttp;
    function createXmlHttpRequest()
    {
      if (window.XmlHttpRequest)
      {
        XmlHttp = new XmlHttpRequest();
      }
      else if (window.ActiveXObject)
      {
        try
        {
        XmlHttp = new ActiveXObject("MsXml2.XmlHTTP");
        }
        catch (e1)
        {
        try
        {
          XmlHttp = new ActiveXObject("Microsoft.XmlHTTP");
        }
        catch (e2)
        {}
        }
      }
      return XmlHttp;    
    }
    function doStart() {
        createXmlHttpRequest();
        var url = "Default2.aspx?task=reset";
        XmlHttp.open("POST", url, true);
        XmlHttp.onreadystatechange = startCallback;
        XmlHttp.send(null);
    }
    function startCallback() {
        if (XmlHttp.readyState == 4) {
          if (XmlHttp.status == 200) {
            setTimeout("pollServer()", 1000);
            refreshTime();
          }
          else {
            alert("HTTP error: "+XmlHttp.status);
          }
        }
    }
    function pollServer() {
        createXmlHttpRequest();
        var url = "Default2.aspx?task=foo";
        XmlHttp.open("POST", 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);
 &