简体   繁体   中英

How to redirect to another page using javascript after successful login?

I need to have a login form that validates and after login the page needs to redirect to a html page. I also need to hard code in a username and password so only with the correct user name/password the page will redirect. If it doesn't have the correct user/pass then I need an alert.

I've tried a bunch of variations but I know I missing something or using the code wrong. Please help! :) Thanks! This is my code so far.

JS:

function validateForm() {
    'use strict';

    // Get references to the form elements:
    var email = document.getElementById('email');
    var password = document.getElementById('password');

    // Validate the login
    if ((email.value.length > 0) && (password.value.length > 0)) {
        return true;
    } else {
        alert('Please complete the form!');
        return false;
    }
}

function check(form) {

    var emailArray = ("myemail@live.com", "");
    var passwordArray = ("MyLogIn", "");

    if (email.value == "email" && password.value == "password") {
        window.open('myaccount.html');
    } else {
        alert('Please enter correct username or password!');
        return false;
    }   
}

function init() {
    'use strict';

    // Confirm that document.getElementById() can be used:
    if (document && document.getElementById) {
        var loginForm = document.getElementById('lgform');
        loginForm.onsubmit = validateForm;
    }
}
window.onload = init;

HTML:

<form action="" method="post" id="lgform">
    <fieldset>
        <legend>Login</legend>
        <div>
            <label for="email">Email Address</label>
            <input type="email" name="email" id="email" required>
        </div>
        <div>
            <label for="password">Password</label>
            <input type="password" name="password" id="password" required>
        </div>
        <div>
            <label for="submit"></label>
            <input type="submit" value="Login" id="submit">
        </div>
    </fieldset>
</form>

Hardcoding the username and password client side is very dangerous - don't do it .

In order to redirect you simply:

window.location = "http://www.google.com/"

however I very much doubt the page you are directing too is secure, can it be accessed directly via the url without passing your authentication?

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