简体   繁体   中英

JS redirection not working as expected

I have a very basic code where I have two HTML pages, index.html being a basic authentication page and crap.html being the page where I do, well, some crap.
Now, I have a form on index.html which has the onsubmit() handler attached to it so that I may check the username and password. If correct, it shows a message and proceeds to redirect the user to crap.html .
Now, the issue is that this redirection seems to work fine for wrong credentials but when given the correct credentials, it automatically reloads the index.html page, even when there is no code for redirection in auth.js .

Here are the codes:


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>  

The reason it's reloading the page is because the form is submitted to the same page. Your form has no action property. To prevent the form from actually submitting, you need to return false; from your submit handler.

Alternatively, set the form action in the submit handler. You can do this easily with jQuery .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM