我是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>

最佳答案

sessionStorage只能存储字符串。您要存储数组的字符串化版本,然后在将它们拉出时遍历它们中的字符。

在存储数据之前将其序列化为JSON,并在读回时使用JSON解析器对其进行解析。

10-04 15:44