简体   繁体   中英

store array of objects in cookie, pure javascript, no jquery?

I am trying to store array of object inside cookie.

Without using jQuery or angular.

function setCook (name,value) {
  var cookie = [name, '=', JSON.stringify(value)].join('');
  document.cookie = cookie;
}

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

Just JSON.parse your return:

https://repl.it/KKoF

function setCook(name, value) {
    var cookie = [
        name,
        '=',
        JSON.stringify(value)
    ].join('');
    document.cookie = cookie;
}

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

setCook('foo', `[
    {
        "qux": "boz"
    },
    {
        "baz": "zot"
    }
]`);
let obj = readCookie('foo');

console.log(obj);

/*
[
    {
        "qux": "boz"
    },
    {
        "baz": "zot"
    }
]
*/

Are you running this in the local file system and not on a server? Cookies are not set when browsing using the file:/// protocol, depending on the browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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