首页 > 解决方案 > 如何使用只有一个正确用户名和一个密码的 HTML 制作登录页面屏幕?

问题描述

我知道您使用 php 使用用户名和密码进行登录,但我仍在学习 HTML,有没有办法用一个正确的用户名和一个正确的密码制作一个使用 HTML 或 JS 硬编码的表单?

例如,如果用户输入用户名 abcd 和密码 pass12345,那么它会进入下一个屏幕,否则会显示“对不起,密码不正确”。

这仅用于学习目的,我知道它根本不安全,不应用于实际网站。只是学习。谢谢 :)

现在的登录页面...

  <form action="loggedin.html">
      <label for="username">Username</label>
      <input
        type="text"
        placeholder="Enter Username"
        name="username"
        required
      />
      <label for="password">Password</label>
      <input
        type="password"
        placeholder="Enter Password"
        name="password"
        required
      />
      <button type="submit">Submit</button>
    </form>

标签: javascripthtmlcssauthentication

解决方案


永远不要在生产中使用 - 仅用于学习目的

由于这仅用于学习目的并且您理解它不安全,因此我继续编写了一个小片段,将检查硬编码的用户名和密码。如果输入的用户名或密码不匹配,它将提醒用户。

我在代码中添加了注释来解释我做了什么以及发生了什么。

见下文

<!-- 
    Added onsubmit attribute to form so that it will trigger the JS function (authenticate). 
    if the function returns false it will prevent the form from submitting 
-->
<form action="loggedin.html" onsubmit="return authenticate()">
      <label for="username">Username</label>
      <!-- added IDs to the inputs -->
      <input
        id="username"
        type="text"
        placeholder="Enter Username"
        name="username"
        required
      />
      <label for="password">Password</label>
      <input
        id="password"
        type="password"
        placeholder="Enter Password"
        name="password"
        required
      />
      <button type="submit">Submit</button>
    </form>
    
    <script>
    
    //Following function gets values of the username and password fields and checks to see if they match a hard coded username and password 
      function authenticate(){
        var authorised;
        
        //get input values
        var username = document.getElementById("username").value;
        var password = document.getElementById("password").value;
        
        //check to see if the password and username match
        if(username == "abcd" && password == "pass12345"){
          authorised = true;
        }else{ // username or password do not match
          authorised = false;
          //alert user
          alert("Sorry, password is incorrect.");
        }
        //return result
        return authorised;
      }
    </script>


推荐阅读