<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異步提交、體驗更好、易維護。