简体   繁体   English

如何使用document.cookie来存储和检索数组中的值?

[英]How do I use document.cookie to store and retrieve the values in an array?

I am storing and retrieving values in cookies using methods: 我正在使用以下方法在Cookie中存储和检索值:

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
};

and

function getCookie() {
    var name = "name=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}; 

Now I need to store/retrieve arrays in a similar fashion. 现在,我需要以类似的方式存储/检索数组。 I know I'll need to create the array as a single string and then parse it back but what is the best way to do this? 我知道我需要将数组创建为单个字符串,然后将其解析回去,但是执行此操作的最佳方法是什么?

I recommend using JSON . 我建议使用JSON First, you convert the array into a JSON string: 首先,将数组转换为JSON字符串:

var array = ["one","two","three"];
var json_string = JSON.stringify(array);

Then you set the cookie with the JSON string as the value. 然后,将JSON字符串作为值来设置cookie。

setCookie("array", json_string, exdays);

Then when you retrieve the JSON string from the cookie later, convert it back into an actual array. 然后,当您稍后从cookie中检索JSON字符串时,请将其转换回实际数组。

var json_string = getCookie("array");
var array = JSON.parse(json_string);

Assuming, you want to store/retrieve multiple cookies.Your get Cookie thing nearly does it: 假设您要存储/检索多个cookie,那么您获得cookie的东西几乎可以做到:

function getCookies() {
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
return ca.map(function(c){
    while (c.charAt(0) == ' ') {
        c = c.substring(1);
    }
        return c.split("=");
    }
});
}; 

You just have to return all, not the first, and you need to remove the namedetection. 您只需要返回全部,而不是第一个,并且需要删除名称检测。

console.log(getCookies());

SetCookies: SetCookies:

function setCookies(Cookies,exp){
 Cookies.forEach(function(el){setCookie(el[0],el[1],exp);});
}

setCookies([
  ["name","value"]
 ]);

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

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