[英]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
很好,但太糟糕了,它仅存储在字符串值中而不是对象值中。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.