「刷新頁面」看似簡單,實則包含:普通刷新、強制刷新(繞過緩存)、自動刷新、框架內刷新、跨窗口刷新(父/子/兄弟)、關閉/打開時刷新等多種場景。本文系統整理所有方案並標註適用場景與坑點。
| 方法 | 代碼 | 特點 | 推薦度 |
|---|---|---|---|
| reload() | location.reload(true) | true=強制從服務端獲取(類似 Ctrl+F5) | ⭐⭐⭐⭐⭐ |
| reload() | location.reload() / location.reload(false) | 從緩存讀取(類似 F5) | ⭐⭐⭐⭐ |
| replace() | location.replace(location.href) | 替換歷史記錄,後退不可回此頁 | ⭐⭐⭐ |
| href 自賦值 | location.href = location.href | 同 reload(false),會保留歷史 | ⭐⭐ |
| assign() | location.assign(location.href) | 同 href 賦值,保留歷史 | ⭐⭐ |
| history.go() | history.go(0) | 同 reload(false) | ⭐⭐ |
| document.execCommand | document.execCommand('Refresh') | 僅 IE 支援,已廢棄 | ❌ |
| window.navigate | window.navigate(location.href) | 僅 IE 支援,已廢棄 | ❌ |
POST 頁面用 location.reload() 會彈出「確認重新提交表單」對話框。
response.sendRedirect(url) 重定向到 GET 頁面,刷新無提示。location.replace(location.href) 替換歷史,刷新不重新提交。<head>
<!-- 20 秒刷新一次 -->
<meta http-equiv="refresh" content="20">
<!-- 20 秒後跳轉 -->
<meta http-equiv="refresh" content="20;url=https://example.com">
</head>
// 1 秒刷新一次
setInterval(function() { location.reload(); }, 1000);
// 5 秒後跳轉
setTimeout(function() { location.href = 'https://example.com'; }, 5000);
// 可控制的倒計時跳轉
var count = 5;
var timer = setInterval(function() {
$('#countdown').text(count--);
if (count < 0) { clearInterval(timer); location.href = '/home'; }
}, 1000);
// 刷新父頁面
parent.location.reload();
// 或
window.opener.location.reload(); // 子窗口刷新父窗口
// 刷新指定 iframe
document.getElementById('myFrame').contentWindow.location.reload();
// 或 jQuery
$('#myFrame')[0].contentWindow.location.reload();
// 刷新同級另一 iframe
parent.frames['otherFrameName'].location.reload();
// parent.otherFrameName.location.reload();
<body onload="opener && opener.location.reload()"> <!-- 打開窗口時刷新父頁 -->
<body onunload="opener && opener.location.reload()"> <!-- 關閉窗口時刷新父頁 -->
// JS 綁定版(推薦)
window.addEventListener('load', function() {
if (window.opener && !window.opener.closed) window.opener.location.reload();
});
window.addEventListener('unload', function() {
if (window.opener && !window.opener.closed) window.opener.location.reload();
});
// 1. 最簡單
Response.Write("");
// 2. 同步 href
Response.Write("");
// 3. 導航到指定頁
Response.Write(""); // 僅 IE
// 局部刷新:AJAX 獲取片段替換
$('#refreshBtn').click(function() {
$.get('/api/data', function(html) {
$('#content').html(html);
});
});
// 或使用 fetch + DOM 更新
async function refreshPartial() {
const res = await fetch('/api/data');
const data = await res.json();
renderUI(data); // 客戶端渲染
}
核心推薦:location.reload(true) 強制刷新、location.replace(url) 避免 POST 重提交、Meta 標簽無 JS 自動刷新、框架用 parent/opener/contentWindow 定位。現代架構下,優先考慮 AJAX 局部更新 或 客戶端狀態管理 替代全頁刷新,體驗更佳、性能更優。