简体   繁体   English

对象变量,用于在页面刷新后保留会话和cookie以外的值

[英]Object variable to retain value after page refresh besides session and cookie

Was wondering whether there are other ways of retaining an object variable after page refresh besides using session and cookie. 想知道除使用会话和cookie外,在页面刷新后是否还有其他方法可以保留对象变量。 Tried window.name but the value become undefined after page refresh. 尝试使用window.name但刷新页面后该值变得不确定。 The localStorage is good but too bad it only store in string value instead of object value. localStorage很好,但太糟糕了,它仅存储在字符串值中而不是对象值中。

reference 参考

You could serialise the object and store in localStorage . 您可以序列化对象并将其存储在localStorage Then when you want to use it again, you unserialise it. 然后,当您想再次使用它时,您将其反序列化。 Here's an example: 这是一个例子:

var myObject = {
   "Hello": "World",
   "Foo": "Bar"
}

localStorage.setItem("myObject", JSON.stringify(myObject));

Then later on, you can retrieve the object from localStorage : 然后,您可以从localStorage检索对象:

var myObject = JSON.parse(localStorage.getItem("myObject"));

For more information, see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify 有关更多信息,请参见https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Found a workaround by using localStorage with JSON.stringify(object) . 通过将localStorageJSON.stringify(object)结合使用找到了一种解决方法。

reference 参考

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

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