我想将 Javascript 数组存储为 Cookie [英] I want to store Javascript array as a Cookie
问题描述
有可能吗,我有一个列表,我想将它存储在浏览器上,如果不可能,这样做的有效方法是什么?
Is it possible, I have a some sort of list and I want to store it on browser, if it is not possible, what is the efficient way of doing this?
推荐答案
JSON 对其进行编码,有效地生成一个类似于 "{name:'myname',age:'myage'}"
的字符串放入 cookie,在需要时检索并解码回 JavaScript 数组/对象.
JSON encode it, effectively producing a string like "{name:'myname',age:'myage'}"
which you put in a cookie, retrieve when needed and decode back into a JavaScript array/object.
示例 - 在 cookie 中存储数组:
Example - store array in a cookie:
var arr = ['foo', 'bar', 'baz'];
var json_str = JSON.stringify(arr);
createCookie('mycookie', json_str);
稍后,以数组形式检索 cookie 的内容:
Later on, to retrieve the cookie's contents as an array:
var json_str = getCookie('mycookie');
var arr = JSON.parse(json_str);
注意: cookie 函数不是原生的,取自 如何从 cookie 创建和读取值?
Note: cookie functions are not native, taken from How do I create and read a value from cookie?
这篇关于我想将 Javascript 数组存储为 Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!