在 Web 應用中,「返回上一頁並刷新」是常見需求,例如用戶提交表單後返回列表頁,期望看到最新數據。本文整理了多種實現方式,涵蓋純 HTML 鏈接、JavaScript 事件、歷史記錄操作、頁面自動刷新/跳轉等場景。
<!-- 簡單返回上一頁 -->
<a href="javascript:history.go(-1)">返回上一頁</a>
<!-- 刷新當前頁面 -->
<a href="javascript:location.reload()">刷新當前頁面</a>
<!-- 返回前兩頁 -->
<a href="javascript:" onclick="history.go(-2);">返回前兩頁</a>
<!-- 返回上一頁並強制刷新(利用 document.referrer) -->
<a href="javascript:" onclick="self.location=document.referrer;">返回上一頁並刷新</a>
<!-- 使用 history.back() -->
<a href="javascript:" onclick="history.back();">返回上一頁</a>
<!-- 點擊跳轉到指定頁面 -->
<button onclick="window.location.href='list.php'">去列表頁</button>
| 方法 | 代碼 | 備註 |
|---|---|---|
| 1. history.go(0) | history.go(0) | 重新加載當前頁面(可能從緩存讀取) |
| 2. location.reload() | location.reload() | 最常用,參數 true 強制從服務器獲取 |
| 3. location=location | location = location | 簡寫,觸發導航 |
| 4. location.assign(location) | location.assign(location) | 同 location.href = location.href |
| 5. document.execCommand('Refresh') | document.execCommand('Refresh') | 僅 IE 支援,已棄用 |
| 6. window.navigate(location) | window.navigate(location) | 僅 IE 支援,非標準 |
| 7. location.replace(location) | location.replace(location) | 替換歷史記錄,無法「返回」 |
| 8. document.URL = location.href | document.URL = location.href | 非標準,不推薦 |
推薦:優先使用 location.reload(true) 強制從服務器重新獲取,或 location.href = location.href 簡潔跨瀏覽器。
<head>
<!-- 每 10 秒自動刷新一次 -->
<meta http-equiv="refresh" content="10">
<!-- 10 秒後跳轉到指定網址 -->
<meta http-equiv="refresh" content="10;url=https://www.baidu.com">
</head>
<script>
function myrefresh() {
window.location.reload();
}
setTimeout('myrefresh()', 1000); // 1 秒後刷新,可改為 setInterval 實現周期性刷新
</script>
<!-- 刷新包含該框架的父頁面 -->
<script> parent.location.reload(); </script>
<!-- 子窗口刷新父窗口 -->
<script> self.opener.location.reload(); </script>
<!-- 或 -->
<a href="javascript:opener.location.reload()">刷新父頁面</a>
<!-- 刷新同級另一個框架 -->
<script> parent.另一FrameID.location.reload(); </script>
<body onload="opener.location.reload()"> <!-- 打開時刷新 -->
<body onUnload="opener.location.reload()"> <!-- 關閉時刷新 -->
<script>
window.opener.document.location.reload();
</script>
location.replace() 時注意用戶無法通過「後退」鍵返回原頁。opener、parent、top 時受同源策略限制,跨域會報錯。