JS重定向未按预期工作

JS redirection not working as expected

本文关键字:工作 重定向 JS      更新时间:2023-09-26

我有一个非常基本的代码,其中有两个HTML页面,index.html是一个基本的身份验证页面,而crap.html是我做一些垃圾的页面
现在,我在index.html上有一个表单,它附带了onsubmit()处理程序,这样我就可以检查用户名和密码。如果正确,它将显示一条消息,并继续将用户重定向到crap.html
现在的问题是,这种重定向似乎对错误的凭据有效,但当提供正确的凭据时,它会自动重新加载index.html页面,即使auth.js中没有重定向代码。

以下是代码:


auth.js

function passCheck(){
var user = document.getElementById("username").value;
var pass = document.getElementById("password").value;
var error = document.getElementById("error");
var set_user = "admin";
var set_pass = "admin";
if(user==set_user && pass==set_pass){
    error.style.color="green";
    error.innerHTML = "AUTHENTICATED CORRECTLY. REDIRECTING NOW.";
    setTimeout(function(){
        window.location.href="../crap.html";
    }, 3000);
}else{
    error.style.color="red";
    error.innerHTML = "WRONG CREDENTIALS. REDIRECTING NOW.";
    setTimeout(function(){
        window.location.href="../index.html";
    }, 1000);
  }
}  

index.html

<html>
<head>
<title>Authentication</title>
    <script src="js/jquery.js"></script>
    <script src="js/auth.js"></script>
    <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
    <form onsubmit="passCheck()">
        <table border=0>
            <tr>
                <td>Username</td>
                <td><input type="text" id="username" placeholder="Username" required autofocus></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" id="password" required></td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="submit" value="AUTHENTICATE">
                </td>
            </tr>
        </table>
    </form>
      <center>
            <div id="error"></div>
      </center>
  </body>
</html>  

它重新加载页面的原因是表单被提交到同一页面。您的表单没有操作属性。为了防止表单实际提交,您需要从提交处理程序中return false;

或者,在提交处理程序中设置表单操作。使用jQuery可以很容易地做到这一点。