JavaScript 原生跳轉方法
1. location.href —— 最常用,保留歷史
window.location.href = "https://example.com";
// 或簡寫
location.href = "https://example.com";
- 產生新歷史記錄,用戶可點「返回」回來
- 同步跳轉,當前頁面卸載
2. location.replace() —— 替換歷史,無法返回
location.replace("https://example.com");
- 不產生新歷史,替換當前記錄
- 適用:登入後跳轉、防止表單重複提交返回
3. location.assign() —— 同 href,但可攔截
location.assign("https://example.com");
- 行為同
href,但可被 beforeunload 取消
4. window.open() —— 新視窗/分頁
// 新分頁/視窗 (受彈窗攔截器影響)
window.open("https://example.com", "_blank");
// 指定視窗特徵
window.open("https://example.com", "newWin", "width=800,height=600,resizable=yes,scrollbars=yes");
5. location.reload() —— 重新載入
location.reload(); // 可能用快取
location.reload(true); // 強制從伺服器獲取
進階模式
條件跳轉:確認對話框
function confirmLogout() {
if (confirm("確定要登出嗎?")) {
location.href = "/logout";
}
}
延遲跳轉
// 5 秒後跳轉
setTimeout(() => location.href = "/home", 5000);
// 倒數顯示
let count = 5;
const timer = setInterval(() => {
document.getElementById("countdown").textContent = count--;
if (count < 0) {
clearInterval(timer);
location.href = "/home";
}
}, 1000);
表單提交跳轉(POST 跳轉)
function postRedirect(url, data) {
const form = document.createElement("form");
form.method = "POST";
form.action = url;
Object.entries(data).forEach(([k, v]) => {
const input = document.createElement("input");
input.type = "hidden";
input.name = k;
input.value = v;
form.appendChild(input);
});
document.body.appendChild(form);
form.submit();
}
// 使用
postRedirect("/api/transfer", { token: "abc", amount: 100 });
伺服器端跳轉對比
PHP
<?php
$url = "https://example.com";
// 1. Header 重導向 (必須在任何輸出前)
header("Location: $url");
exit; // 關鍵:防止後續代碼執行
// 2. HTML Meta 刷新 (可延遲)
?>
<meta http-equiv="refresh" content="5;url=<?= $url ?>">
<?php
ASP.NET (WebForms / MVC)
// WebForms
Response.Redirect("~/Default.aspx");
// MVC
return Redirect("https://example.com");
return RedirectToAction("Index", "Home");
Java Servlet
response.sendRedirect("https://example.com");
// 或
request.getRequestDispatcher("/WEB-INF/view.jsp").forward(request, response); // 伺服器端轉發
避坑指南
| 問題 | 原因 | 解決 |
| Header 已發送錯誤 | PHP 輸出空白/HTML 前調用 header() | 確保 header() 前無任何 echo/空白/HTML |
| window.open 被攔截 | 瀏覽器彈窗攔截器 | 用戶主動點擊事件中調用、或引導用戶允許 |
| location.href 不跳轉 | 在 iframe 中、或 JS 錯誤中斷 | 用 top.location.href 穿透 iframe |
| 單頁應用 (SPA) 跳轉 | 需用 Router API,非 location | Vue: router.push() / React: navigate() |
最佳實踐清單
- 優先
location.href(保留歷史)或 replace()(不保留)
- 跳轉前清理資源:
localStorage、計時器、WebSocket、EventListener
- POST 敏感操作用表單提交,避免 URL 洩露參數
- SPA 內部導航用 Router,外部鏈接用
location.href
- 提供降級:
<a href="..."> 確保無 JS 也能跳轉