如何使用 jQuery $.cookie() 将对象数组存储在 cookie 中?
我有一个 javascript 对象列表:
var people = [
{ 'name' : 'Abel', 'age' : 1 },
{ 'name' : 'Bella', 'age' : 2 },
{ 'name' : 'Chad', 'age' : 3 },
]
我尝试使用 jQuery $.cookie() 将它们存储在浏览器 cookie 中:
$.cookie("people", people);
然后检索此 cookie,然后尝试将另一个对象推入其中:
var people = $.cookie("people");
people.push(
{ 'name' : 'Daniel', 'age' : 4 }
);
但是,这不起作用;我在 Firebug 中分析了这段代码,控制台指出 people
是一个字符串 ("[object Object],[object Object],[object Object]"
),并且推送功能不存在。
到底是怎么回事?存储和检索对象列表的正确方法是什么?
I have a list of javascript objects:
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():
$.cookie("people", people);
I then retrieve this cookie and then try to push another object into it:
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.
What is going on? What is the proper way to store and retrieve a list of objects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我今天尝试了这一点,但无法让它发挥作用。后来我发现这是因为我有3个非常大的对象,我试图将它们保存在cookie中。
我解决这个问题的方法是将信息存储在浏览器的本地存储中。
示例:
有关本地存储的更多信息:cookie 与本地存储
我的 4 小时时间发泄到此,不要犯同样的错误。
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.
The way I worked arround this was by storing the information in the browsers local storage.
example:
further info about local storage: cookies vs local storage
4 hours of my time vent to this, dont make the same mistake.
Cookie 只能存储字符串。因此,您需要将对象数组转换为 JSON 字符串。如果您有 JSON 库,则只需使用
JSON.stringify(people)
并将其存储在 cookie 中,然后使用$.parseJSON(people)
取消字符串化它。最后,您的代码将如下所示:
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.In the end, your code would look like: