萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 頁面跳轉完全指南:location、open、replace 及跨語言對比

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,非 locationVue: router.push() / React: navigate()

最佳實踐清單

  1. 優先 location.href(保留歷史)或 replace()(不保留)
  2. 跳轉前清理資源:localStorage、計時器、WebSocket、EventListener
  3. POST 敏感操作用表單提交,避免 URL 洩露參數
  4. SPA 內部導航用 Router,外部鏈接用 location.href
  5. 提供降級:<a href="..."> 確保無 JS 也能跳轉
copyright © 萬盛學電腦網 all rights reserved