javascript - 如何使用只有一个正确用户名和一个密码的 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>
解决方案
永远不要在生产中使用 - 仅用于学习目的
由于这仅用于学习目的并且您理解它不安全,因此我继续编写了一个小片段,将检查硬编码的用户名和密码。如果输入的用户名或密码不匹配,它将提醒用户。
我在代码中添加了注释来解释我做了什么以及发生了什么。
见下文
<!--
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>
推荐阅读
- python - Plotly:嵌入散点图/网络图标记的条形图
- imagemagick - 在一行中转换和组合多个图像 Imagemagick (windows)
- android - 如何在 Camera2 Api 上运行 2 个不同的预览?
- .net-core - 使用 dotnet ef 迁移添加 Initial -s 找不到 DbContext 类
-C -o - python - 博弈论在生成对抗网络中的用途在哪里
- javascript - GeoLocation API 在离线模式下不工作
- wso2-am - 登录时出现 WSO2 API Manager 授权问题
- r - 如何转换二分网络并使用一级节点属性作为 igraph (R) 中二级节点的边权重
- php - Google Places Nearby API Success 200,但在 Laravel 中返回“INVALID_REQUEST”
- python - 如何使用 tf.keras 获取每个 train_step 的详细运行时间?