简体   繁体   English

如何使用jQuery $ .cookie()在cookie中存储对象数组?

[英]How do I store an array of objects in a cookie with jQuery $.cookie()?

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中分析了这段代码,并且控制台注意到people是一个字符串( "[object Object],[object Object],[object Object]" )并且push函数不存在。

What is going on? 到底是怎么回事? What is the proper way to store and retrieve a list of objects? 存储和检索对象列表的正确方法是什么?

Cookies can only store strings. Cookie只能存储字符串。 Therefore, you need to convert your array of objects into a JSON string. 因此,您需要将对象数组转换为JSON字符串。 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. 如果你有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));

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: 例:

localStorage.setItem("test2", JSON.stringify(obj) )

localStorage.getItem("test2")

further info about local storage: cookies vs local storage 有关本地存储的更多信息: cookies与本地存储

4 hours of my time vent to this, dont make the same mistake. 我4小时的时间发泄,不要犯同样的错误。

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

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