简体   繁体   中英

Set cookie with array() in jquery

I would like to be able to check if a cookie (id) is set or not: if not set, then create it. If set, retrieve the value (= an array). How can I retrieve the array from the cookie? I hear that I would have to use JSON, but I'm not sure how that would work with the following code?

function start(id){
 if (document.cookie.indexOf('id') === -1 ) {
     setCookie('id', id, 7);
    } 
 else {
    var playedID = [GET COOKIE ARRAY]
    playedID.push(id); 
    setCookie('id',playedID);
  } 
}

Here's a way to do it based on some helper functions to make sure you are parsing and stringifying the cookie correctly.

getCookie and setCookie are from https://www.w3schools.com/js/js_cookies.asp

 // This won't run due to security policies on this site, but you can run it in the dev tools and see. function getCookie(cname) { var name = cname + "="; 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 ""; } 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=/"; } function getCookieArray(cname) { var cookie = getCookie(cname); return cookie? JSON.parse(cookie): []; } function pushToCookieArray(cname, cvalue, exdays) { var cookieArray = getCookieArray(cname); cookieArray.push(cvalue); setCookie(cname, JSON.stringify(cookieArray), exdays); } function start(id) { pushToCookieArray('id', id, 7); console.log(getCookieArray('id')); } start(5); start(6); start(8);

  1. First a cookie is not stored as an array but a string: if you type document.cookie in you console, you will get all the cookies from the website you are visiting, separated with a coma.

So as explained here: https://www.w3schools.com/js/js_cookies.asp , you will have to create a custom function to access the cookie you need.

  1. Then the value of you cookie is still a string, so as explained here if you want to save an array of ids, you have to use JSON.stringify to encode you array as a string: I want to store Javascript array as a Cookie

You can then create it or update its value:


function getCookie(cname) {
  var name = cname + "=";
  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 "";
}

function setCookie(cname, cvalue) {
  document.cookie = cname + "=" + cvalue + ";";
}

function start(id){
 if (getCookie('id') === '' ) {
     setCookie('id', JSON.stringify([+id]));
    }
 else {
    let ids = JSON.parse(getCookie('id'))
    console.log(ids)
    ids.push(+id); 
    setCookie('id', JSON.stringify(ids));
  } 
}

function sendID(id) {
  console.log(document.getElementById("user-id").value)
  start(id);
  alert(getCookie("id"))
}

Here is a working example: https://codepen.io/adrientiburce/pen/ExVbYWy?editors=1010

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