您的位置:首页 > 编程语言 > C#

通过C#+AJAX实现倒计时

2007-09-17 23:23 281 查看
一、页面部分代码

     <%@ Page Language="C#" AutoEventWireup="true" CodeFile="CountDown.aspx.cs" Inherits="CountDown" %>

<!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" language=javascript>
  
          var url;
          var xmlHttp;
        function createXMLHttpRequest()
        {
            if(window.ActiveXObject)
            {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            else if(window.XMLHttpRequest)
            {
                xmlHttp = new XMLHttpRequest();
            }
        }   
   
        //刷新
        function refurbish()
        {
           var url="GetTime.ashx";
           createXMLHttpRequest();
           xmlHttp.open("POST",url,true);
           xmlHttp.onreadystatechange=Olympiad;
           xmlHttp.send(null);
           setTimeout("refurbish('"+url+"')",1000);
        }   
 
        //获取2008奥运会倒计时的时间
       function Olympiad()
       {  
          
             if(xmlHttp.readyState==4)
            {
                if(xmlHttp.status==200)
                {
                    document.getElementById("show").innerHTML=xmlHttp.responseText;
                }
            }          
           
       }    

 </script>
</head>
<body onload="refurbish()">
    <h3 align="center">奥运倒计时</h3>
    <form id="form1" runat="server">
    <div id="show"> </div>
    </form>
</body>
</html>

二、AJAX代码部分

     <%@ WebHandler Language="C#" Class="GetTime" %>

using System;
using System.Web;

public class GetTime : IHttpHandler {
   
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";

        //当前时间
        DateTime date=System.DateTime.Now;
        
        //奥运开幕时间
        DateTime date2 = new DateTime(2008,8,8,19,0,0);

        //获取两个时间之间的间隔   
        TimeSpan ts = date2.Subtract(date)

        String message = "今天距2008奥运会开幕还有:<font color='darkred'>"+ts.Days.ToString()+"</font>天 ";
        message += "<font color='darkred'>"+((ts.Hours<10)?("0"+ts.Hours.ToString()):ts.Hours.ToString())+"</font>小时 ";
        message += "<font color='darkred'>" + ((ts.Minutes < 10) ? ("0" + ts.Minutes.ToString()) : ts.Minutes.ToString()) + "</font>分 ";
        message += "<font color='darkred'>" + ((ts.Seconds < 10) ? ("0" + ts.Seconds.ToString()) : ts.Seconds.ToString()) + "</font>秒"

        context.Response.Write(message);
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息