简体   繁体   English

使用 Javascript,我试图将数据保存在浏览器的 SessionStorage 和 localStorage 中,但刷新页面后数据丢失

[英]Using Javascript, I am trying to persist the data in SessionStorage and localStorage of browser but after refreshing the page the data is lost

I am adding array of movie objects to session storage in below line as:我在下面的行中将电影对象数组添加到 session 存储中:

sessionStorage.setItem('MyMovieList', JSON.stringify(movies)); sessionStorage.setItem('MyMovieList', JSON.stringify(movies));

Could someone figure out what is wrong in the code because of which session storage is not working as expected?有人能找出代码中的问题是因为 session 存储没有按预期工作吗?

<!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width", initial-scale=2.0">
            <meta http-equiv="X-UA-Compatible" content="ie=edge">
            <title>Putting User input into JS Objects</title>
            <style>
    
            </style>
        </head>
        <body>
            <form>
                <div class="formBox">
                    <label for="title">Movie</label>
                    <input type="text" id="title" placeholder="Title"/>
                </div>
                <div class="formBox>
                    <label for="yr">Year</label>
                    <input type="number" id="yr" placeholder="Year"/>
                </div>
                <div class="formBox">
                    <button id="btn">Click to Add</button>
                </div>
                <div id="msg">
                    <pre></pre>
                </div>
            </form>
            <script>
                let movies = [];
                const addMovie = (ev) => {
                    ev.preventDefault();//to stop the form submission
    
                    let movie = {
                        id: Date.now(),
                        title: document.getElementById('title').value,
                        year: document.getElementById('yr').value
                    }
    
                movies.push(movie);
                document.forms[0].reset();// to clear the form for next entry
                //document.querySelector('form').reset();
                //for display purpose only
                console.warn('added', {movies} );
                let pre =  document.querySelector('#msg pre');
                pre.textContent = '\n' + JSON.stringify(movies, '\t', 2);
                
                //saving to localStorage
                //localStorage.setItem('MyMovieList', JSON.stringify(movies ));
    
                //saving to sessionStorage
                sessionStorage.setItem('MyMovieList', JSON.stringify(movies));
                }
                 document.addEventListener('DOMContentLoaded', () => {
                   document.getElementById('btn').addEventListener('click',addMovie);
                 });
    
            </script>
        </body>
    </html>

So I copied your code and ran it locally and everything worked fine, the movies are stored in the section.因此,我复制了您的代码并在本地运行它,一切正常,电影存储在该部分中。 The problem you are having is that你遇到的问题是

`let pre =  document.querySelector('#msg pre');
            pre.textContent = '\n' + JSON.stringify(movies, '\t', 2);`

is inside the clickHandler so on refresh if you want to see what you had in you session you can just click the button and it will be displayed within the pre tag again.位于 clickHandler 内,如果您想查看session中的内容,请刷新,您只需单击按钮,它将再次显示在pre标记中。 try this instead试试这个

  <script>
let movies = [];
const addMovie = (ev) => {
  ev.preventDefault();//to stop the form submission

  let movie = {
    id: Date.now(),
    title: document.getElementById('title').value,
    year: document.getElementById('yr').value
  }

  movies.push(movie);
  document.forms[0].reset();// to clear the form for next entry
  //document.querySelector('form').reset();
  //for display purpose only
  console.warn('added', { movies });

  //saving to localStorage
  //localStorage.setItem('MyMovieList', JSON.stringify(movies ));

  //saving to sessionStorage
  sessionStorage.setItem('MyMovieList', JSON.stringify(movies));

  let pre = document.querySelector('#msg pre');
  pre.textContent = '\n' + sessionStorage.getItem('MyMovieList'),
    '\t', 2;
}
document.addEventListener('DOMContentLoaded', () => {
  document.getElementById('btn').addEventListener('click', addMovie);
  let pre = document.querySelector('#msg pre');
  pre.textContent = '\n' + sessionStorage.getItem('MyMovieList'),
    '\t', 2;
});

In the addMovie function just save to the sessioStorage and display to again, meanwhile on refresh you the DOMContentLoaded just display whatever you had in the sessionStore .addMovie function 中,只需保存到sessioStorage并再次显示,同时刷新你的DOMContentLoaded只显示你在sessionStore中的任何内容。

NB - you might want to format the output the way you want and maybe refactor the duplicate code into a function to make it DRY, I hope this suggestions is useful and can unblock you so that you can continue building your amazing app.注意 - 您可能想要按照您想要的方式格式化 output 并且可能将重复的代码重构为 function 以使其干燥,我希望这些建议有用并且可以解除阻止您,以便您可以继续构建您的惊人应用程序。 #cheers #干杯

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM