在 ASP.NET 網頁中實現「N 秒後自動跳轉」純屬前端行為,伺服端僅需輸出倒數初始值與目標 URL。本文提供純 JavaScript 實作、jQuery 版本、以及伺服端動態注入倒數參數的完整範例,並討論使用 location.replace 避免歷史堆疊的細節。
<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>
<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>
.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) 不會在瀏覽器歷史留下紀錄,使用者按「上一頁」不會回到倒數頁,體驗較佳。document.getElementById 而非 textContent (用 innerText)。setTimeout 字串參數傳遞函數名稱 (如 setTimeout("tick()", 1000)),應直接傳函數參考。此技巧常用於登入成功頁、付款完成頁、錯誤提示頁等需延遲導向的場景,純前端實作、零伺服端負擔。