點擊登入按鈕 → 彈出提示文字 → 跳轉至指定頁面。
<button id="btnLogin" onclick="login()">登入</button>
<script>
function login() {
alert("登入成功!");
window.location.href = "https://example.com/dashboard"; // 替換為目標 URL
}
</script>
<form id="loginForm" onsubmit="return handleLogin(event)">
<input type="text" id="username" placeholder="用戶名" required />
<input type="password" id="password" placeholder="密碼" required />
<button type="submit">登入</button>
</form>
<script>
async function handleLogin(event) {
event.preventDefault(); // 阻止表單預設提交跳轉
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
// 簡單前端驗證
if (!username || !password) {
alert("請輸入用戶名和密碼");
return false;
}
try {
const response = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
const result = await response.json();
if (result.success) {
alert("登入成功!歡迎 " + result.user.name);
// 儲存 token (localStorage/cookie)
if (result.token) localStorage.setItem('auth_token', result.token);
// 跳轉
window.location.href = result.redirectUrl || "/dashboard";
} else {
alert("登入失敗:" + result.message);
}
} catch (err) {
alert("網路錯誤,請稍後再試");
console.error(err);
}
return false; // 防止表單提交
}
</script>
| 方法 | 代碼 | 特性 |
|---|---|---|
| location.href | window.location.href = url | 同步跳轉,保留歷史記錄,可回上頁 |
| location.replace | window.location.replace(url) | 替換歷史,無法回上頁(適合登入後) |
| location.assign | window.location.assign(url) | 同 href,但可作為函數調用 |
| 表單 target | <form action="url" target="_blank"> | 新分頁開啟 |
簡單需求用 alert() + location.href 即可。生產環境**必須**採用 AJAX 異步登入 + 後端驗證 + Token 儲存 + 安全跳轉。前端僅負責收集輸入、顯示狀態、引導跳轉,核心認證邏輯在後端。