通过表单强制 window 重定位 - JavaScript

Force window relocation through a form - JavaScript

我正在构建一个假的登录表单,如果用户插入正确的凭据,它应该在本地加载一个不同的 url。这是 html 代码:

<div class="container">
    <h2>Login page - Welcome</h2>   
    <form id="loginForm" onsubmit="subLogin()">
        Username: <input id="userName" type="text" name="userName" required><br/>
        Password: <input id="passWord" type="password" name="password" required><br/>
        <button type="submit" id="login-button" value="Login">Login</button>
    </form>
</div>

这是我尝试通过 window.location.href = "/index.html" 重新定位用户的 javascript

function subLogin() {
    var userName = document.getElementById('userName').value;
    var passWord = document.getElementById('passWord').value;
    if (userName !== 'mickeymouse' || passWord !== 'DisneyLand') {
        alert('Your username or password is not correct');
    } else {
        window.location.href = 'http://localhost:8000/index.html';
    };
};

如果用户名或密码错误,但如果它们是正确的,window.location 将无法正常工作。

有没有办法用纯 javascript 解决这个问题,还是通过 ajax 使用 XMLHttp GET Request 更好?预先感谢您的回复!

我设法解决了这个问题。我只是将表格更改为:

<form id="loginForm" action="javascript:subLogin()"></form>

我post 代码以防将来有人需要它。无论如何感谢您的回复!