使用 javascript 在 cookie 中创建数组 [英] Create array in cookie with javascript
问题描述
是否可以使用数组创建 cookie?
Is it possible to create a cookie using arrays?
我想存储 a[0]='peter'
, a['1']='esther'
, a['2']='john'
在 JavaScript 的 cookie 中.
I would like to store a[0]='peter'
, a['1']='esther'
, a['2']='john'
in a cookie in JavaScript.
推荐答案
正如您在此主题中所读到的那样:
您结合使用 jQuery.cookie 插件和 JSON 并解决您的问题.
You combine the use jQuery.cookie plugin and JSON and solve your problem.
当你想存储一个数组时,你在JS中创建一个数组并使用JSON.stringify
将其转换为字符串并与$.cookie('name', 'array_string')
When you want to store an array, you create an array in JS and use JSON.stringify
to transform it into an string and stored with $.cookie('name', 'array_string')
var myAry = [1, 2, 3];
$.cookie('name', JSON.stringify(myAry));
当您想检索 cookie 中的数组时,使用 $.cookie('name')
检索 cookie 值并使用 JSON.parse
检索字符串中的数组.
When you want to retrive the array inside the cookie, you use $.cookie('name')
to retrive the cookie value and use JSON.parse
to retrive the array from the string.
var storedAry = JSON.parse($.cookie('name'));
//storedAry -> [1, 2, 3]
这篇关于使用 javascript 在 cookie 中创建数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!