首页 > 解决方案 > 使用 if/else 语句 (JavaScript) 登录后如何重定向用户?

问题描述

我正在学习 JavaScript,所以我决定做一个简单的 if/else 语句登录的小项目。一切都很好,但它没有重定向。

如果您知道我做错了什么,请用简单的语言帮助我,因为我正在学习它。

'use strict'
function validate(){
    var username=document.getElementById('login-username').value;
    var passowrd=document.getElementById('login-password').value;

    if (username === "daksh" && passowrd === 'daksh'){
        alert('You have sucessfully logged in');
        window.location.href("http://stackoverflow.com");
    } else{
        alert('Wrong username or password');
        return true;
    }
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="login.css">
  <title>Login</title>
  <script src="login.js"></script>
</head>

<body>
  <DIV class="container">
    <form method="POST" class="login-form">
      <h1 class="login-heading">LOGIN FORM</h1>
      <input type="text" placeholder="User Name" id="login-username">
      <br><br>
      <input type="password" placeholder="Password" id="login-password">
      <br><br><br>
      <input type="submit" value="Login" id="login-submit" onclick="validate()">
    </form>
  </DIV>

</body>

</html>

标签: javascripthtmlif-statementauthentication

解决方案


  1. 始终在表单上使用提交事件处理程序,从不使用提交按钮 - 您希望在出现错误时阻止提交,或者在您的情况下阻止提交,因为您正在自己处理处理
  2. 使用eventListener而不是内联事件处理程序
  3. 您使用 location.href 作为函数,它不是。location.replace(href)如果你愿意,你可以使用
  4. 出于明显的安全原因,不要进行客户端密码验证,但我认为这只是为了学习目的

window.addEventListener("load", function() { // when the page has loaded
  document.getElementById("myForm").addEventListener("submit", function(e) { // passing the event
    e.preventDefault(); // you do not want to let the form submit because you handle the nex page 
    const username = document.getElementById('login-username').value;
    const password = document.getElementById('login-password').value;

    if (username === "daksh" && password === 'daksh') {
      alert('You have sucessfully logged in');
      window.location.href = "http://stackoverflow.com";
    } else {
      alert('Wrong username or password');
    }
  })
})
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="login.css">
  <title>Login</title>
  <script src="login.js"></script>
</head>

<body>
  <div class="container">
    <form method="POST" class="login-form" id="myForm">
      <h1 class="login-heading">LOGIN FORM</h1>
      <input type="text" placeholder="User Name" id="login-username">
      <br><br>
      <input type="password" placeholder="Password" id="login-password">
      <br><br><br>
      <input type="submit" value="Login" id="login-submit">
    </form>
  </div>

</body>

</html>


推荐阅读