星期五, 5月 02, 2008

網頁上計時..時間到了..執行server端程式

在討論去看到的問題..就把簡單範例寫出來..參考一下ㄅ..

.aspx 放span來顯示剩餘時間..linkbutton是來呼叫server端程式用的

<body>
<form id="form1" runat="server">
<div>
<span id="num">剩餘時間:</span>
<br />
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click"></asp:LinkButton>
</div>
</form>
</body>

.cs 這裡就把要註冊到頁面上的js丟上去ㄅ..

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;

public partial class test_jsDoSomething : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
StringBuilder sb = new StringBuilder();

//這裡是你從資料庫會其他地方所抓出來的時間
sb.AppendLine("var ttime = 70; ");

//主程式
sb.AppendLine("var secs = 0; ");
sb.AppendLine("var hour= 0; ");
sb.AppendLine("var min = 0; ");
sb.AppendLine("var t = false; ");
sb.AppendLine(" ");
sb.AppendLine("close_myself(); ");
sb.AppendLine("var id = setInterval('close_myself()',1000); ");
sb.AppendLine(" ");
sb.AppendLine("function close_myself() ");
sb.AppendLine("{ ");
sb.AppendLine(" if(ttime != '') ");
sb.AppendLine(" { ");
sb.AppendLine(" if(!t) ");
sb.AppendLine(" { ");
sb.AppendLine(" secs = ttime; ");
sb.AppendLine(" secs--; ");
sb.AppendLine(" document.getElementById('num').innerHTML = GetTime(secs); ");
sb.AppendLine(" t = true; ");
sb.AppendLine(" } ");
sb.AppendLine(" else ");
sb.AppendLine(" { ");
sb.AppendLine(" secs--; ");
sb.AppendLine(" document.getElementById('num').innerHTML = GetTime(secs); ");
sb.AppendLine(" } ");
sb.AppendLine(" if(secs<=0) ");
sb.AppendLine(" { ");
sb.AppendLine(" clearTimeout(id); ");
sb.AppendLine(" ");

//__doPostBack('LinkButton1','')這是去呼叫server端的LinkButton1_Click的程式
sb.AppendLine(" __doPostBack('LinkButton1','') ");

sb.AppendLine(" } ");
sb.AppendLine(" } ");
sb.AppendLine("} ");
sb.AppendLine("function GetTime(sec) ");
sb.AppendLine("{ ");
sb.AppendLine(" hour = Math.floor(sec / 3600); ");
sb.AppendLine(" min = Math.floor(sec / 60); ");
sb.AppendLine(" if(sec >= 60) ");
sb.AppendLine(" { ");
sb.AppendLine(" min= Math.floor(sec/60); ");
sb.AppendLine(" sec= sec % 60; ");
sb.AppendLine(" } ");
sb.AppendLine(" if(min>=60) ");
sb.AppendLine(" { ");
sb.AppendLine(" hour= Math.floor(min/60); ");
sb.AppendLine(" min = min % 60; ");
sb.AppendLine(" } ");
sb.AppendLine(" return '剩餘時間:' + hour+ ':' +min +':'+sec; ");
sb.AppendLine("} ");

ClientScript.RegisterStartupScript(GetType(), "test", sb.ToString(), true);
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
//就是把js在丟出來
ClientScript.RegisterStartupScript(GetType(), "123", "alert('我執行啦我執行啦!!')", true);
}
}

完成..Open-mouthed..

沒有留言: