GetTime

出自 ProgWiki
前往: 導覽搜尋

用途

  1. 傳回現在伺服器時間。
  2. 保持網頁的Session不致於TimeOut。(需在網頁端,定時以AJAX方式,抓回此getTime.ashx的傳回值)

程式碼

  • 檔案:getTime.ashx
<%@ WebHandler Language="C#" Class="getTime" %>
 
using System;
using System.Web;
using System.Web.SessionState;
 
public class getTime : IHttpHandler, IRequiresSessionState
{
 
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
		string strNow = DateTime.Now.ToString("T");
		context.Session["Now"] = strNow;
		context.Response.Write(strNow);
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}

使用範例

  • 這個範例所使用的 prototype.js 可以從這裡下載
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="index" %>
 
<!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 id="Head1" runat="server">
<title></title>
<script type="text/javascript" src="JavaScript/prototype.js"></script>
<script type="text/javascript">
/*<![CDATA[*/
 
    //保持連線用
    function getNow()
    {
		var x= new Ajax.Request('getTime.ashx',
		{
			method:'get',
			onSuccess: function(transport){
				$('LabelNow').innerHTML = transport.responseText;
			},
			onFailure: function(){ 
				$('LabelNow').innerHTML = '連線中斷,<br/>請關閉瀏覽器, 重新登入!';
			}
		});
    }
 
    var membersTimer = window.setInterval("getNow()", 1000);
/*]]>*/ 
</script>
</head>
<body>
    <form id="form1" runat="server">
    <p align="center">
	<asp:Label ID="LabelNow" runat="server" Text="" Width="100px"></asp:Label>
    </p>
    </form>
</body>
</html>