简体   繁体   English

如何使用JavaScript将数据持久保存在数组中,即使页面重新加载也是如此?

[英]How to persist data in an array even when the page reloads, using javascript?

I have created a register and a login form using html and javascript. 我已经使用html和javascript创建了一个注册器和一个登录表单。 Where I am storing the user data in an array and then in local storage. 我将用户数据存储在数组中,然后存储在本地存储中的位置。 For this I have initially declared an empty array called var users=[]; 为此,我最初声明了一个名为var users = []的空数组; Thus, when the page reloads the previously stored data is lost as array becomes empty again and data in the local storage is overwritten. 因此,当页面重新加载时,先前存储的数据将丢失,因为数组再次变空,并且本地存储中的数据将被覆盖。 Please help, on how to avoid the array become empty after reloading the page. 请帮忙,如何避免在重新加载页面后数组变空。

Following is my controller.js- 以下是我的controller.js-

//Declaring an empty array
var users = [];

//Setting id for each users
var idInput = makeCounter();

//Fetching data from textboxes in register.html
var firstnameInput  = document.getElementById("firstname");
var lastnameInput   = document.getElementById("lastname");
var emailInput      = document.getElementById("email");
var usernameInput   = document.getElementById("username");
var passwordInput   = document.getElementById("password");
var dobInput        = document.getElementById("dob");
var messageBox      = document.getElementById("editeddata");

//Declaring custom constructor function
function userdetails(id, firstname, lastname, email, dob, username, password){
    this.id         = id;
    this.firstname  = firstname;
    this.lastname   = lastname;
    this.email      = email;
    this.dob        = dob;
    this.username   = username;
    this.password   = password;
    this.FullName   = this.firstname +' ' + this.lastname;
}

//counter funtion, to fetch user id
function makeCounter() {
    var arraylength=users.length;
    return function(){
        return arraylength+1;
    }
}

//insert data while registration
function registerUser()
{
    //Email validation
    var emailinput = document.forms["myform"]["email"].value;
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    if(!(emailinput).match(emailReg) || emailinput=="")
    {
        alert("Not a valid e-mail address");
        return false;

    }
    //check, if fields are empty
    if(firstnameInput.value=="" || lastnameInput.value=="" || passwordInput.value=="" || dobInput.value=="")
    {
        alert("Fields cannot be empty");
        return false;
    }

    //check, if a user already exist
    var usernameinput = document.forms["myform"]["username"].value;
    var passwordinput = document.forms["myform"]["password"].value;
    var ulen= users.length;
    for(i=0; i < ulen; i++)
    {
        if ( usernameinput == users[i].username && passwordinput == users[i].password)
        {
            alert("User already exists");
            return false;
        }
    }

    var user=new userdetails(idInput(),firstnameInput.value, lastnameInput.value, emailInput.value, dobInput.value, usernameInput.value, passwordInput.value);
    users.push(user);
    alert("Registered successfully");
    localStorage.setItem("key_users", JSON.stringify(users));

}

You can use local storage value at the time of initialisation. 您可以在初始化时使用本地存储值。

if (typeof(Storage) !== "undefined") {
  if (localStorage.key_users) {
    users = localStorage.key_users;
  } else {
    users = [];
  }
}

you can use something like this to check if the key is already in localStorage or not. 您可以使用类似的方法来检查密钥是否已经在localStorage中。

<html>
  <head>

    <link href="style.css" rel="stylesheet">
  </head>
  <body onload="test()">


    <script>
    function test(){
        var value = (localStorage.getItem("key1"))
        console.log(value)
       if(value == null){
           localStorage.setItem("key1","value1")
           alert("Hellow")
       }else{
           var value=localStorage.getItem("key1");
           alert(value)
       }

    }


    </script>
  </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Html 获取 selectedindex 值并在页面重新加载后保留它 - Html Get the selectedindex value and persist it even after the page reloads 页面重新加载时Javascript无法正常工作 - Javascript is not working when page reloads 当您的页面javascript重新加载元素时,如何应用等待时间 - How to apply wait time when Your page javascript reloads the element 页面重新加载时如何取回设置的数据 - How to get back the set data when page reloads 即使在 Jquery 中刷新页面,如何保持 setInterval 函数? - How to persist setInterval function even when page is refreshed in Jquery? 重新载入页面时,Javascript更改重置 - Javascript changes reset when page reloads JavaScript-存储页面重新加载时的倒计时等 - JavaScript - Store countdown for when page reloads etc 页面重新加载时的Javascript倒计时问题 - Javascript countdown problems when page reloads 即使重新加载网页,如何在Javascript中保留变量的值? - How can I keep a value for a variable in Javascript, even when the webpage reloads? 即使重新加载,如何使用Javascript从Firefox Scratchpad控制其他窗口? - How can I use Javascript to control other window from Firefox Scratchpad, even when it reloads?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM