「五秒後自動返回上一頁」、「每十秒刷新一次內容」、「表單送出後跳去別頁」——這些都是常見需求。JavaScript 提供了好幾種寫法,另外 HTML 的 meta refresh 也能達到類似效果,以下整理成對照表。
<SCRIPT LANGUAGE="JavaScript">
var time = 5; // 秒數
var timelong = 0;
function diplaytime(){
document.all.his.innerHTML = time - timelong; // 時間遞減
timelong++;
}
function redirect(){
window.location.href = "Category-list"; // 目標頁面
}
timer = setInterval('diplaytime()', 1000); // 每秒更新顯示
timer = setTimeout('redirect()', time * 1000); // 到秒數後跳轉
</SCRIPT>
搭配的頁面片段:
<DIV ALIGN="CENTER" style="font-size:15;color:threeddarkshadow;"> 如果你不執行任何操作,系統會在 5 秒後自動返回! </DIV> <DIV ALIGN="CENTER" style="font-size:15;color:threeddarkshadow;" id="his"> 5 秒鐘後自動返回..... </DIV>
用 meta 標籤:
<meta http-equiv="refresh" content="10;url=跳轉的頁面">
content 的第一個數字代表等待秒數,url 則是要載入的位址。
用 JavaScript 重新載入:
<script>window.location.reload(true);</script>
若要刷新某個 iframe,把 window 換成該 frame 的名稱或 id 即可。
指定網址:
<script>window.location.href="yourpage.aspx";</script>
用 setTimeout 週期性跳轉:
function abc() {
window.location.href = "/blog/window.location.href";
setTimeout("abc()", 10000);
}
刷新本頁 / 父頁 / 指定頁(後端輸出):
// 刷新本頁
Response.Write("<script>window.location.href=window.location.href;</script>")
// 刷新開啟它的父視窗
Response.Write("<script>opener.location.href=opener.location.href;</script>")
// 轉到指定頁
Response.Write("<script>window.location.href='yourpage.aspx';</script>")
1. setTimeout
<script>setTimeout("location.href='url'",2000)</script>
2000 是等待毫秒數,即兩秒。
2. meta refresh
<meta name="Refresh" content="n;url">
n 是等待秒數,url 是要載入的絕對位址。
3. 後端 redirect
<%response.redirect url%>
常用來在表單或參數判斷某操作完成後轉址。
4. 刷新框架頁
<script language=javascript>top.leftFrm.location.reload();parent.frmTop.location.reload();</script>
彈出視窗後刷新母頁,或只刷新框架的某一側:
Response.Write("<script language=javascript>");
Response.Write("parent.left.location.href='PayDetailManage_Left.aspx'");
Response.Write("</script>");
若在子視窗頁面中處理,可在 head 加入 <base target="_self"/> 避免框架層級混淆。
<!-- 1. HTML:每 10 秒刷新 -->
<META HTTP-EQUIV="Refresh" content="10">
<!-- 2. JSP:每秒刷新 -->
<% response.setHeader("refresh","1"); %>
<!-- 3. JavaScript:每秒刷新 -->
<script language="javascript">setTimeout("self.location.reload();",1000);</script>
<!-- 20 秒後跳到指定網址 --> <meta http-equiv="refresh" content="20;url=https://自己的URL">
定時刷新這類做法在今天要慎用。頁面自動刷新會打斷使用者填寫、干擾螢幕閱讀器,也可能讓表單重複送出。若只是要更新局部資料,改用 AJAX 輪詢或 WebSocket 會是更好的選擇;若確實需要跳轉倒數(例如登出提示),也建議提供「取消」或「留在本頁」的按鈕,並用 aria-live 告知剩餘時間。