简体   繁体   English

将数组存储到Cookie jQuery

[英]Store Array to Cookie Jquery

I am creating an array in my code which looks like this 我正在我的代码中创建一个数组,看起来像这样

Array [ "type", "year", "week" ]

When I save this to a cookie and read it again it formats as 当我将其保存到Cookie并再次读取时,其格式为

Array [ "type,year,week" ]

How can I keep the original format Array [ "type", "year", "week" ] I guess it is getting stripped down to a CSV when it is added to the cookie. 我如何保持原始格式Array [ "type", "year", "week" ]我猜想当它添加到cookie中时,它会被简化为CSV。

Thanks in advance 提前致谢

My code: 我的代码:

var myArray = [ "type", "year", "week" ]
$.cookie('setup', myArray, { path: '/' }); // set up cookie 

Cookies store string values. Cookies存储字符串值。

You need to serialize your array (with JSON or join with a predefined delimiter) before storing it into a cookie and deserialize it when reading it back. 您需要先将数组序列化(使用JSON或使用预定义的分隔符联接),然后再将其存储到cookie中并在读回时对其进行反序列化。

For example: 例如:

// store into cookie
$.cookie('setup', myArray.join('|'), { path: '/' });
OR
$.cookie('setup', JSON.stringify(myArray), { path: '/' });

// read from cookie
myArray = $.cookie('setup').split('|');
OR
myArray = JSON.parse($.cookie('setup'));

Note : The JSON versions are safer since they'll work with any kind of array. 注意 :JSON版本更安全,因为它们可以与任何类型的数组一起使用。 The former assumes that your array elements do not contain | 前者假定您的数组元素不包含| in them. 在他们中。

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

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