Javascript 如何使用 jQuery $.cookie() 在 cookie 中存储对象数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9040110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I store an array of objects in a cookie with jQuery $.cookie()?
提问by dangerChihuahua007
I have a list of javascript objects:
我有一个 javascript 对象列表:
var people = [
{ 'name' : 'Abel', 'age' : 1 },
{ 'name' : 'Bella', 'age' : 2 },
{ 'name' : 'Chad', 'age' : 3 },
]
I tried to store them in a browser cookie with jQuery $.cookie():
我尝试使用 jQuery $.cookie() 将它们存储在浏览器 cookie 中:
$.cookie("people", people);
I then retrieve this cookie and then try to push another object into it:
然后我检索这个 cookie,然后尝试将另一个对象推入其中:
var people = $.cookie("people");
people.push(
{ 'name' : 'Daniel', 'age' : 4 }
);
However, this does not work; I analyzed this code in Firebug, and Console noted that people
was a string ("[object Object],[object Object],[object Object]"
) and that the push function did not exist.
但是,这不起作用;我在 Firebug 中分析了这段代码,Console 注意到这people
是一个字符串 ( "[object Object],[object Object],[object Object]"
) 并且推送函数不存在。
What is going on? What is the proper way to store and retrieve a list of objects?
到底是怎么回事?存储和检索对象列表的正确方法是什么?
回答by Kevin B
Cookies can only store strings. Therefore, you need to convert your array of objects into a JSON string. If you have the JSON library, you can simply use JSON.stringify(people)
and store that in the cookie, then use $.parseJSON(people)
to un-stringify it.
Cookie 只能存储字符串。因此,您需要将对象数组转换为 JSON 字符串。如果您有 JSON 库,您可以简单地使用它JSON.stringify(people)
并将其存储在 cookie 中,然后使用$.parseJSON(people)
它来取消字符串化。
In the end, your code would look like:
最后,您的代码将如下所示:
var people = [
{ 'name' : 'Abel', 'age' : 1 },
{ 'name' : 'Bella', 'age' : 2 },
{ 'name' : 'Chad', 'age' : 3 },
];
$.cookie("people", JSON.stringify(people));
// later on...
var people = $.parseJSON($.cookie("people"));
people.push(
{ 'name' : 'Daniel', 'age' : 4 }
);
$.cookie("people", JSON.stringify(people));
回答by ThunD3eR
I attempted this today and could not get it to work. Later i found out that it was because I had 3 very large objects which I tried to save in a cookie.
我今天尝试了这个,但无法让它工作。后来我发现这是因为我试图将 3 个非常大的对象保存在 cookie 中。
The way I worked arround this was by storing the information in the browsers local storage.
我的工作方式是将信息存储在浏览器的本地存储中。
example:
例子:
localStorage.setItem("test2", JSON.stringify(obj) )
localStorage.getItem("test2")
further info about local storage: cookies vs local storage
有关本地存储的更多信息:cookie 与本地存储
4 hours of my time vent to this, dont make the same mistake.
我有 4 个小时的时间来发泄这个,不要犯同样的错误。