我想存储JavaScript数组作为Cookie [英] I want to store Javascript array as a Cookie
本文介绍了我想存储JavaScript数组作为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' '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.
数组中的数组:
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屋!
查看全文