我是JavaScript和这个网站的新手,我正在尝试模拟用户名和密码登录和创建者。目前,用户名和密码创建者仅限于预先制作的用户名和密码。最后,我们的想法是在一个页面上创建用户名和密码,然后将该用户名和密码数组发送到登录页面。我知道安全性很差,我不会在真实的网站上使用它,但除此之外,我无法运行代码。代码输出用户名和密码文本框以放入值,但是当您单击按钮以拥有它们时,没有任何反应。我做错了什么?谢谢你的帮助!
宣布预先制作的用户名和密码的页面:
<!DOCTYPE html>
<html>
<head>
<title>
create account
</title>
<script>
sessionStorage.setItem( "username1", ["bob", "sam"]);
sessionStorage.setItem( "password1", ["lol", "jk"]);
</script>
</head>
<body>
</body>
</html>
在日志中发送和处理用户名和密码数组的位置:
<!DOCTYPE html>
<html>
<head>
<title>
log on page
</title>
<script type = "text/javascript">
var count = 2;
function validate() {
var un = document.getElementById("username").value
var pw = document.getElementById("pword").value
var valid = false;
var unArray = sessionStorage.getItem("username1");
var pwArray = sessionStorage.getItem("password1");
for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = true;
break;
}
}
if (valid) {
alert ("Login was successful");
window.location = "http://www.google.com";
return false;
}
var t = " tries";
if (count == 1) {t = " try"}
if (count >= 1) {
alert ("Invalid username and/or password. " +
"You have " + count + t + " left.");
document.myform.username.value = "";
document.myform.pword.value = "";
setTimeout("document.myform.username.focus()", 25);
setTimeout("document.myform.username.select()", 25);
count --;
}
else {
alert ("Still incorrect! You have no more tries left!");
document.myform.username.value = "No more tries allowed!";
document.myform.pword.value = "";
document.myform.username.disabled = true;
document.myform.pword.disabled = true;
return false;
}
}
</script>
<!--this-->
<style>
p.log_on{
position: fixed;
top: 30px;
left: 20px;
}
</style>
</head>
<body>
<!--here-->
<form name = "myform">
<p class="log_on">
ENTER USER NAME <input type="text" id="username"><br><br><br><br><br>
ENTER PASSWORD <input type="password" id="pword">
<input type="button" value="Check In" name="Submit" onclick="validate()">
</p>
</form>
<!--to here-->
</body>
</html>
答案 0 :(得分:1)
sessionStorage
只能存储字符串。您正在存储数组的字符串化版本,然后在将它们拉回时循环遍历它们中的字符。
在存储数据之前将数据串行化为JSON,并在读回时用JSON解析器解析它。