首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

JavaScript 登入按鈕事件:提示彈窗與頁面跳轉完整實現

     編輯:程式設計綜合問答

需求

點擊登入按鈕 → 彈出提示文字 → 跳轉至指定頁面。

基礎實現


<button id="btnLogin" onclick="login()">登入</button>

<script>
function login() {
    alert("登入成功!");
    window.location.href = "https://example.com/dashboard";  // 替換為目標 URL
}
</script>

進階:表單驗證 + AJAX 異步登入(推薦生產環境)


<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.hrefwindow.location.href = url同步跳轉,保留歷史記錄,可回上頁
location.replacewindow.location.replace(url)替換歷史,無法回上頁(適合登入後)
location.assignwindow.location.assign(url)同 href,但可作為函數調用
表單 target<form action="url" target="_blank">新分頁開啟

安全提醒

  • 永不在前端儲存/驗證密碼:必須後端驗證,回傳 JWT/Session ID
  • HTTPS 傳輸:防止密碼明文竊聽
  • CSRF 保護:雙重提交 Cookie 模式或 SameSite Cookie
  • 防暴力破解:後端限制嘗試次數、驗證碼、帳號鎖定

總結

簡單需求用 alert() + location.href 即可。生產環境**必須**採用 AJAX 異步登入 + 後端驗證 + Token 儲存 + 安全跳轉。前端僅負責收集輸入、顯示狀態、引導跳轉,核心認證邏輯在後端。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved