页面加载时获取localStorage的值

3

我在互联网上搜索了很多,但好像没有找到适合我的东西。

以下是代码:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Heating System Control</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script>
        strLED1 = "";
        strLED2 = "";
        strText1 = "";
        strText2 = "";
        var LED1_state = 0;
        var LED2_state = 0;
        function GetArduinoIO()
            {
                nocache = "&nocache=" + Math.random() * 1000000;
                var request = new XMLHttpRequest();
                request.onreadystatechange = function()
                {
                    if (this.readyState == 4) {
                        if (this.status == 200) {
                            if (this.responseXML != null) 
                            {
                            // XML file received - contains analog values, switch values and LED states
                                document.getElementById("input1").innerHTML =
                                    this.responseXML.getElementsByTagName('analog')[0].childNodes[0].nodeValue;
                                document.getElementById("input2").innerHTML =
                                    this.responseXML.getElementsByTagName('analog')[1].childNodes[0].nodeValue;
                                // LED 1
                                if (this.responseXML.getElementsByTagName('LED')[0].childNodes[0].nodeValue === "on") {
                                    document.getElementById("LED1").innerHTML = "ON";
                                    document.getElementById("LED1").style.backgroundColor = "green";
                                    document.getElementById("LED1").style.color = "white";
                                    LED1_state = 1;
                                }
                                else {
                                    document.getElementById("LED1").innerHTML = "OFF";
                                    document.getElementById("LED1").style.backgroundColor = "red";
                                    document.getElementById("LED1").style.color = "white";
                                    LED1_state = 0;
                                }
                                // LED 2
                                if (this.responseXML.getElementsByTagName('LED')[1].childNodes[0].nodeValue === "on") {
                                    document.getElementById("LED2").innerHTML = "ON";
                                    document.getElementById("LED2").style.backgroundColor = "green";
                                    document.getElementById("LED2").style.color = "white";
                                    LED2_state = 1;
                                }
                                else {
                                    document.getElementById("LED2").innerHTML = "OFF";
                                    document.getElementById("LED2").style.backgroundColor = "red";
                                    document.getElementById("LED2").style.color = "white";
                                    LED2_state = 0;
                                }
                            }
                        }
                    }
                }
                // send HTTP GET request with LEDs to switch on/off if any
                request.open("GET", "ajax_inputs" + strLED1 + strLED2 + nocache, true);
                request.send(null);
                setTimeout('GetArduinoIO()', 1000);
                strLED1 = "";
                strLED2 = "";
            }
        function GetButton1()
            {
                if (LED1_state === 1) 
                {
                    LED1_state = 0;
                    strLED1 = "&LED1=0";
                }
                else 
                {
                    LED1_state = 1;
                    strLED1 = "&LED1=1";
                }
            }
        function GetButton2()
            {
                if (LED2_state === 1) 
                {
                    LED2_state = 0;
                    strLED2 = "&LED2=0";
                }
                else 
                {
                    LED2_state = 1;
                    strLED2 = "&LED2=1";
                }
            }
        function SendText1()
            {
                nocache = "&nocache=" + Math.random() * 1000000;
                var request = new XMLHttpRequest();

                strText2 = "&txt2=" + document.getElementById("txt_form1").form_text1.value + "&end2=end";

                request.open("GET", "ajax_inputs" + strText2 + nocache, true);
                request.send(null);
            }
        function SendText2()
            {
                nocache = "&nocache=" + Math.random() * 1000000;
                var request = new XMLHttpRequest();

                strText1 = "&txt1=" + document.getElementById("txt_form2").form_text2.value + "&end1=end";

                request.open("GET", "ajax_inputs" + strText1 + nocache, true);
                request.send(null);
            }
        function clsTxt1()
            {
            setTimeout(
              function clearTxt()
              {
                  document.getElementById("txt_form1").form_text1.value = "";
              }, 500)
            }
        function clsTxt2()
            {
            setTimeout(
              function clearTxt()
              {
                  document.getElementById("txt_form2").form_text2.value = "";
              }, 500)
            }
        function Threshold1()
        {
            var thr1 = document.getElementById("txt_form1").form_text1.value;
            document.getElementById("thresh1").innerHTML = thr1;
        }
        function Threshold2()
            {
                var thr2 = document.getElementById("txt_form2").form_text2.value;
                document.getElementById("thresh2").innerHTML = thr2;
            }
    </script>
    <style>
        .IO_box 
        {
            float: left;
            margin: 0 20px 20px 0;
            border: 1px solid black;
            padding: 0 5px 0 5px;
            width: 100px;
            height: 196px;
            text-align: center;
        }
        h1 
        {
            font-family: Helvetica;
            font-size: 120%;
            color: blue;
            margin: 5px 0 10px 0;
            text-align: center;
        }
        h2 
        {
            font-family: Helvetica;
            font-size: 85%;
            color: black;
            margin: 10px 0 5px 0;
            text-align: center;
        }
        p, form
        {
            font-family: Helvetica;
            font-size: 80%;
            color: #252525;
            text-align: center;
        }
        button
        {
            font-family: Helvetica;
            font-size: 80%;
            max-width: 100px;
            width: 90px;
            height: 25px;
            margin: 0 auto;
            text-align: center;
            border: none;
        }
        input
        {
            font-family: Helvetica;
            font-size: 80%;
            max-width: 100px;
            width: 90px;
            height: 25px;
            margin: 0 auto;
            text-align: center;
            border: none;
        }
        .small_text 
        {
            font-family: Helvetica;
            font-size: 70%;
            color: #737373;
            text-align: center;
        }
        textarea
        {
            resize: none;
            max-width: 90px;
            margin-bottom: 1px;
            text-align: center;
        }
    </style>
    </head>
    <body onload="GetArduinoIO(); Threshold1()">
        <h1>Heating System Control</h1>
        <div class="IO_box">
            <h2>Room One</h2>
            <p>Temp1 is: <span id="input1">...</span></p>
            <button type="button" id="LED1" onclick="GetButton1()" color="white" backgroundColor="red" style="border: none;">OFF</button><br /><br />
            <form id="txt_form1" name="frmText">
                <textarea name="form_text1" rows="1" cols="10"></textarea>
            </form>
            <input type="submit" value="Set Temp" onclick="SendText1(); clsTxt1(); Threshold1();" style ="background-color:#5F9EA0" />
            <p>Threshold: <span id="thresh1">...</span></p>
        </div>
        <div class="IO_box">
            <h2>Room Two</h2>
            <p>Temp2 is: <span id="input2">...</span></p>
            <button type="button" id="LED2" onclick="GetButton2()" color="white" backgroundColor="red" style="border: none;">OFF</button><br /><br />
            <form id="txt_form2" name="frmText">
                <textarea name="form_text2" rows="1" cols="10"></textarea>
            </form>
            <input type="submit" value="Set Temp" onclick="SendText2(); clsTxt2(); Threshold2();" style ="background-color:#5F9EA0" />
            <p>Threshold: <span id="thresh2">...</span></p>
        </div>

    </body>
</html>

所以我的问题是,如何在重新加载页面后(从“Threshold1()”函数中)保留插入文本区域中的值?我找到了一些使用“localStorage”和JQuery的示例,但我不知道如何在重新加载页面时调用保存的值。
任何帮助都将不胜感激。
提前致谢, Stefan。

1
localStorage.getItem()?MDN:https://developer.mozilla.org/zh-CN/docs/Web/API/Storage - Máté Safranka
1
我应该在哪里放置代码?我需要在页面加载时获取值,并将其打印在页面的<body>部分。 - user9477865
1
用户在文本区域中输入内容后,您可以通过读取文本区域的值并使用localStorage.setItem('threshold1', valueFromTextArea);将其存储在本地存储中。然后,在页面加载时,您可以使用var storedValue = localStorage.getItem('threshold1');检索该值,并在任何需要的位置写入它。setItem()中的第一个参数可以是任何字符串,第二个参数是要存储的值。然后,您可以将该字符串传递给getItem()以检索存储的值。 - Máté Safranka
3个回答

2

本地存储解释

localStorage对象喜欢存储字符串,那么如何存储大型对象,比如一些复杂的数据结构?很简单,JavaScript内置了一个很棒的函数,查找JSON.stringify(object)。因此,您只需要像下面提供的代码一样存储一些复杂对象即可。然后,要从localStorage检索对象,您将想要使用JSON.parse(object);

要了解localStorage,我强烈建议您查看MDN,如果您想了解JSON.parseJSON.stringify函数,您也可以在这里找到它们:

  1. JSON.parse() 链接
  2. JSON.stringify() 链接

// vanilla js version of $(document).ready(function(){/*code here*/});
window.ready = function(fnc) {
  if (typeof fnc != "function") {
    return console.error("You need to pass a function as a param.");
  }

  try { // try time out for some old IE bugs
    setTimeout(function () {
      document.addEventListener("DOMContentLoaded", fnc());
    }, 10)
  } catch (e) {
    try { // sometimes timeout won't work
      document.addEventListener("DOMContentLoaded", fnc());
    } catch (ex) {
      console.log(ex);
    }
  }
};

// shorter than $(document).ready();
ready(function() {
  var object = {
      name: "Jack",
      age: 30,
      location: "U.S.A.",
      get_pay: function() {
        console.log("test");
      }
    },
    test;

  console.log(object);

  var obj_string = JSON.stringify(object);

  // run a test
  var run_test = function() {
    // output the stored object 
    test = localStorage.getItem("test");
    console.log(test);

    // to make js turn it into an object again 
    test = JSON.parse(localStorage.getItem("test"));
    console.log(test);
  };


  // demo of trying to store an actual object
  try {
    localStorage.setItem("test", object);
    run_test();
  } catch (e) {
    console.log(e);
  }

  // demo of trying to store the string
  try {
    localStorage.setItem("test", obj_string);
    run_test();
  } catch (e) {
    console.log(e);
  }
});


我尝试使用stringify,但是像上面的评论一样,我没有问题与html文件中的“<script>”部分。我不知道如何在页面加载时调用保存的变量值,在“<body>”部分。 - user9477865
好的,首先我添加了一个函数来确保DOM已经加载(ready)。这样一来,它将在DOM中的所有内容加载完成后运行,不包括图片等内容。所以你只需要使用ready函数就可以了吗? - JO3-W3B-D3V
@StefanKostoski 我突然想到,你为什么要包含一个jQuery脚本,而实际上你并没有真正使用它呢?这对我来说似乎有点奇怪。 - JO3-W3B-D3V
哦,对不起,我忘记把它删除了。当我尝试使用jQuery完成我的任务时,它还在那里。 - user9477865

1
你可以使用这个JSFiddle:http://jsfiddle.net/xpvt214o/45115/ 在这里,我们使用“Cookie”概念和“jquery.cookie.js”来完成你想要做的事情。
为了正确检查fiddle,你需要每次按“Run”,你可以在2个选项卡中打开相同的fiddle,在第一个fiddle中写入一些内容,然后只需在第二个fiddle选项卡中按下运行按钮,值应该自动更新,这里的$(function(){});复制了你的页面加载。

1
这完全依赖于jQuery,但这个解决方案并没有完全回答他的问题,因为他确切地询问了关于localStorage的问题。我的意思是,你的解决方案没有任何问题,如果你想支持超级老的浏览器,那么这比我自己的解决方案更好。此外,如果你想使用cookie,我不明白为什么你不会只使用vanilla JS,避免依赖于jQuery...这样更轻量级...我选择远离jQuery的唯一原因是它相当臃肿,但同时也是有意为之的,所以... - JO3-W3B-D3V
1
是的,我完全同意你的观点。但是使用Jquery可以使代码看起来更加简洁优雅,避免了编写原生JS的麻烦。而且正如你所预期的那样,它被编写成支持旧版浏览器并可在多个平台上运行。 - Narendra Selot
1
正如他在问题中提到的,他正在寻找在页面加载后仍然保持值完整的选项。所以这也可能是其中的一个替代方案,非常感谢您的答案,我也从中学到了一些新的东西 :) - Narendra Selot
1
不用谢和Touché,但就我个人而言,我拒绝甚至尝试支持比IE9更旧的任何东西。 我知道IE9实际上可以使用 localStorage 因为我曾在一个商业项目中使用过。 至于 jQuery 是否更整洁,这是有争议的,但它确实可以节省你编写自己的功能代码。 但就我个人而言,我觉得那部分很有趣!;) ....公平地说,我并不讨厌 jQuery,它是一个非常好的一揽子解决方案,但我认为它实际上并不擅长一件具体的事情,因为公平来说,它不是为此而制作的! :) - JO3-W3B-D3V
请将实际答案发布在此处,使用“[<>]”标记。我知道它不处理localStorage,但是jsfiddle链接会变得陈旧-例如,它们现在使用https。 - mplungjan
显示剩余2条评论

0

我的问题没有得到确切的答案,但我完全避免在设备上存储信息。现在我只是直接从Arduino读取值,它可以工作。但还是感谢每个提供帮助的人。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接