萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 搭配 JavaScript 實現倒數計時自動跳轉頁面

在 ASP.NET 網頁中實現「N 秒後自動跳轉」純屬前端行為,伺服端僅需輸出倒數初始值與目標 URL。本文提供純 JavaScript 實作、jQuery 版本、以及伺服端動態注入倒數參數的完整範例,並討論使用 location.replace 避免歷史堆疊的細節。

純 JavaScript 實作 (無相依)

<div id="autoRedirect">
  頁面將在 <span id="countdown" style="color:red">5</span> 秒後自動跳轉至
  <a id="targetLink" href="https://example.com">目標頁面</a>
  <br /><br />
  <a href="https://example.com" style="color:fuchsia">立即跳轉 >></a>
</div>

<script>
  (function() {
    var seconds = 5;
    var url = "https://example.com";
    var $countdown = document.getElementById("countdown");
    var $link = document.getElementById("targetLink");

    function tick() {
      $countdown.textContent = seconds;
      if (seconds <= 0) {
        location.replace(url); // 不保留歷史,避免「回上一頁」回到倒數頁
        return;
      }
      seconds--;
      setTimeout(tick, 1000);
    }
    tick();
  })();
</script>

jQuery 版本 (專案已引用 jQuery 時)

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(function() {
    var seconds = 5;
    var url = "https://example.com";
    var $countdown = $("#countdown");
    var timer = setInterval(function() {
      $countdown.text(seconds);
      if (seconds <= 0) {
        clearInterval(timer);
        location.replace(url);
      }
      seconds--;
    }, 1000);
  });
</script>

ASP.NET 伺服端動態注入參數

.aspx.cs:

public partial class RedirectPage : System.Web.UI.Page {
    protected int CountdownSeconds = 5;
    protected string RedirectUrl = "https://example.com";

    protected void Page_Load(object sender, EventArgs e) {
        // 可從 QueryString、資料庫、Session 取得動態值
        if (int.TryParse(Request.QueryString["s"], out int s)) CountdownSeconds = s;
        if (!string.IsNullOrEmpty(Request.QueryString["url"])) RedirectUrl = Request.QueryString["url"];
    }
}

.aspx:

<script>
  (function() {
    var seconds = <%= CountdownSeconds %>;
    var url = "<%= RedirectUrl %>";
    var $countdown = document.getElementById("countdown");
    function tick() {
      $countdown.textContent = seconds;
      if (seconds <= 0) { location.replace(url); return; }
      seconds--; setTimeout(tick, 1000);
    }
    tick();
  })();
</script>

進階:倒數期間顯示動態訊息 / 取消跳轉

var timerId = setInterval(tick, 1000);
$("body").on("click", ".cancel-redirect", function() {
    clearInterval(timerId);
    $("#autoRedirect").html("已取消自動跳轉,請手動點選上方連結。");
});

注意事項

  • location.replace(url) 不會在瀏覽器歷史留下紀錄,使用者按「上一頁」不會回到倒數頁,體驗較佳。
  • 若需支援舊版 IE (≤9),請改用 document.getElementById 而非 textContent (用 innerText)。
  • 避免在 setTimeout 字串參數傳遞函數名稱 (如 setTimeout("tick()", 1000)),應直接傳函數參考。

此技巧常用於登入成功頁、付款完成頁、錯誤提示頁等需延遲導向的場景,純前端實作、零伺服端負擔。

copyright © 萬盛學電腦網 all rights reserved