我想将 Javascript 数组存储为 Cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2980143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:46:42  来源:igfitidea点击:

I want to store Javascript array as a Cookie

javascriptjquerycookies

提问by Oguz Bilgic

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?

是否有可能,我有某种列表,我想将它存储在浏览器上,如果不可能,这样做的有效方法是什么?

回答by George Kagan

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.

JSON 对其进行编码,有效地生成一个字符串,就像"{name:'myname',age:'myage'}"您放入 cookie 一样,在需要时检索并解码回 JavaScript 数组/对象。

Example - store array in a cookie:

示例 - 将数组存储在 cookie 中:

var arr = ['foo', 'bar', 'baz'];
var json_str = JSON.stringify(arr);
createCookie('mycookie', json_str);

Later on, to retrieve the cookie's contents as an array:

稍后,以数组形式检索 cookie 的内容:

var json_str = getCookie('mycookie');
var arr = JSON.parse(json_str);

Note:cookie functions are not native, taken from How do I create and read a value from cookie?

注意:cookie 函数不是原生的,取自如何从 cookie 创建和读取值?

回答by Daniel Vassallo

One quick method is to join()your array into a single string, using an appropriate delimiter:

一种快速方法是join()使用适当的分隔符将数组转换为单个字符串:

var a = [1, 2, 3, 4];
a.join('|');  // Returns: "1|2|3|4"

Then simply use the string split()method to get the array back from the cookie string.

然后只需使用 stringsplit()方法从 cookie 字符串中取回数组。

回答by David Wong

For each value id in an array, please try below method to save a value in a cookie array:

对于数组中的每个值 id,请尝试以下方法将值保存在 cookie 数组中:

<script type="text/javascript">

/**
 * set cookie
 */
function set_cookie(cookiename, cookievalue, hours) {
    var date = new Date();
    date.setTime(date.getTime() + Number(hours) * 3600 * 1000);
    document.cookie = cookiename + "=" + cookievalue + "; path=/;expires = " + date.toGMTString();

}

set_cookie('item['+id+']', id, 24*365*10); // 10 years

</script>

And you can retrieve this array in php:

你可以在 php 中检索这个数组:

<?php
foreach($_COOKIE['item'] as $e){
echo $e,'<br />';
}
?>