protected void Binddata()
{
// this.mytext.InnerHtml="三秒後頁面跳轉<div id=\"aa\"></div>";//也可以在頁面固定一個DIV地區來顯示該資訊
Response.Write("三秒後頁面跳轉<div id=\"aa\"></div>");//先產生一個用來顯示時間倒計時的DIV
StringBuilder sb = new StringBuilder();//注意添加using引用 System.Text
sb.Append("<script langage=\"javascript\">"); //用\"轉義'
sb.Append("var i=4;");
sb.Append("function out()");
sb.Append("{");
sb.Append("if(i>0){ ");
sb.Append("i--;}");
sb.Append("else {");
sb.Append("location.href=\"login.aspx\";}");//這裡的login.aspx可以隨便改成你想轉換的頁面
sb.Append("document.getElementById(\"aa\").innerHTML=i; }");
sb.Append("setInterval(\"out()\",1000); "); //每隔一秒發生
sb.Append("</script>");
this.Page.Controls.Add(new LiteralControl(sb.ToString()));
}
需要再通用一點的話,把方法參數提出來後如下,各頁面調用也方便很多
public static void SuccessReturnScript(System.Web.UI.Page page,string writeControlID,string returnUrl)
{
StringBuilder sb = new StringBuilder();
sb.Append("<script langage=\"javascript\">"); //用\"轉義'
sb.Append("var i=4;");
sb.Append("function out()");
sb.Append("{");
sb.Append("if(i>1){ ");
sb.Append("i--;}");
sb.Append("else {");
sb.Append("location.href=\"" + returnUrl + "\";}");
sb.Append("document.getElementById(\"" + writeControlID + "\").innerHTML=\"操作成功,頁面<font color=red>\"+i+\"</font>秒後自動跳轉\"; }");
sb.Append("setInterval(\"out()\",1000); "); //每隔一秒發生
sb.Append("</script>");
page.Controls.Add(new LiteralControl(sb.ToString()));
}
另外加一個倒計時顯示的js代碼
為了最佳化,day只計算了一次。hour,minitus,second,ms則放在裡層反覆計算
<script type="text/javascript">
var day=hour=minitus=second=ms=0;
var targetDate= new Date("2010/08/07 12:00:00");
var tmp = targetDate - new Date();
day = Math.floor(tmp / 86400000);
function RefreshTime()
{
tmp = (targetDate - new Date()) % 86400000;
hour=Math.floor(tmp/3600000);
tmp%=3600000;
minitus=Math.floor(tmp/60000);
tmp%=60000;
second=Math.floor(tmp/1000);
// ms=tmp-1000*second;
document.getElementById("m1").innerHTML = "距離" + targetDate + "年還有 " + day + " 天 " + hour + " 小時 " + minitus + " 分 " + second + " 秒 ";
}
setInterval(RefreshTime, 1000);
</script>