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

HTML表單提交驗證失敗?缺少return導致頁面跳轉異常

     編輯:程式設計綜合問答

問題代碼

<form name="myform" action="###" method="post" onsubmit="check()">
    <input type="text" name="name" />
    <input type="password" name="pw" />
    <input type="submit" value="登錄" />
</form>

<script>
function check() {
    if (document.forms[0].name.value == "123" && document.forms[0].pw.value == "123456") {
        window.location = "body.html";
    } else {
        alert("用戶名或密碼錯誤");
        return false;
    }
}
</script>

核心錯誤

onsubmit="check()" 缺少 return。瀏覽器執行 `check()` 後,無論返回什麼,表單都會繼續提交(導致頁面跳轉/刷新),`window.location` 跳轉被後續提交打斷。

修正方案

<form ... onsubmit="return check()">

同時 `check()` 必須顯式返回 boolean:

function check() {
    if (document.forms[0].name.value == "123" && document.forms[0].pw.value == "123456") {
        window.location = "body.html";
        return false; // 阻止默認提交,由JS手動跳轉
    } else {
        alert("用戶名或密碼錯誤");
        return false; // 阻止提交
    }
    // 成功情況下也返回false,因為已手動跳轉
    // 若需正常提交表單到服務器驗證,成功時 return true
}

最佳實踐:分離驗證與跳轉

<form id="loginForm" action="/login" method="post">
    <input type="text" name="username" required />
    <input type="password" name="password" required />
    <button type="submit">登錄</button>
</form>

<script>
document.getElementById('loginForm').addEventListener('submit', async (e) => {
    e.preventDefault(); // 阻止默認提交
    const formData = new FormData(e.target);
    try {
        const resp = await fetch('/login', { method: 'POST', body: formData });
        if (resp.ok) {
            window.location.href = '/dashboard';
        } else {
            alert('登錄失敗');
        }
    } catch (err) {
        alert('網絡錯誤');
    }
});
</script>

優勢:HTML5原生驗證(`required`)、Fetch異步提交、體驗更好、易維護。

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