取消表单提交后,windows .location.href仍然不能工作

window.location.href still not working after cancelling form submission

本文关键字:不能 工作 href location 表单提交 windows 取消      更新时间:2023-09-26

我有一个登录表单

<div id='login_form'>
        <table>
            <tr>
                <td>Username:</td>
                <td><input size=25 type='text' id='username'></td>  
            </tr>
            <tr>
                <td>Password:</td>
                <td><input size=25 type='password' id='password'></td>
            </tr>
            <tr>
                <td colspan='2' align='right'>
                      <input type='button' id='login' value='Login' onkeydown='normalobjKeyFunc(this)' onfocus='itemFocus(this)'                                                  onblur='itemBlur(this)'/>
                </td>
            </tr>
        </table>
</div>

然后是javaScript

var input_username = document.getElementById("username").value;
var input_password = document.getElementById("password").value;
if(input_username === "123" && input_password === "456"){
    alert("Correct username & password");
    window.location.href="../../result.html";
    return false;
}

但是当我收到"正确的用户名&,页面没有重定向到result.html。我检查了"../../result。html"存在。

  1. 我发现有些人说应该取消提交,所以我删除了表单,并将登录按钮的"type = "submit"更改为"type = "button",但它不起作用。
  2. 还有另一种方法,在"window.location.href="../../result.html" "之后添加"return false",但它不能正常工作。

有人知道吗????提前感谢!

用户名/密码检查应该在后端 (Java, PHP, Node, .NET)

你的表单应该在表单标签中。检查应该在onsubmit回调中完成:

<script>
    function authenticate(){
        var input_username = document.getElementById("username").value;
        var input_password = document.getElementById("password").value;
        if(input_username==="123"&&input_password==="456"){
            alert("Correct username & password");
            window.location.href = "../../result.html";
        }
        else {
            // Error
        }
        return false;
    }
</script>
<form onsubmit="authenticate()">
    <table>
        <tr>
            <td>Username:</td>
            <td><input size="25" type="text" id="username"></td>  
        </tr>
        <tr>
            <td>Password:</td>
            <td><input size="25" type="password" id="password"></td>
        </tr>
        <tr>
            <td colspan="2" style="text-align: right">
                <button onkeydown="normalobjKeyFunc(this)" onfocus="itemFocus(this)" onblur="itemBlur(this)">Login</button>
            </td>
        </tr>
    </table>
</form>

在你的按钮中添加一个onclick来调用javascript函数。

<input type='button' id='login' onclick="authenticate()" value='Login' onkeydown='normalobjKeyFunc(this)' onfocus='itemFocus(this)' onblur='itemBlur(this)'/>