Create array in cookie with javascript

后端 未结 9 870
-上瘾入骨i
-上瘾入骨i 2020-12-08 10:32

Is it possible to create a cookie using arrays?

I would like to store a[0]=\'peter\', a[\'1\']=\'esther\', a[\'2\']=\'john\' i

9条回答
  •  囚心锁ツ
    2020-12-08 11:00

    For that example you can do it quite easily:

    • Make Cookies:

      ///W3Schools Cookie Code:
      function setCookie(cname,cvalue,exdays) {
          var d = new Date();
          d.setTime(d.getTime() + (exdays*24*60*60*1000));
          var expires = "expires=" + d.toGMTString();
          document.cookie = cname + "=" + cvalue + ";" + expires + ";";
      }
      
      function getCookie(cname) {
          var name = cname + "=";
          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);
              }
              if (c.indexOf(name) == 0) {
                  return c.substring(name.length, c.length);
              }
          }
          return "";
      }
      
      ///My Own Code:
      for(a=0;a
    • Retrieve Array:

      for(a=0;a

    For any array with other value types besides strings:

    • Make Cookies:

      ///Replace MyCode above With:
      if(typeof b[a] === 'string'){
          setCookie(b[a],b[a],periodoftime);
      }else{
          setCookie(b[a].toString,b[a],periodoftime);
      }
      
    • Retrieve Array:

      for(a=0;a

    The only flaw is that identical values cannot be retrieved.

    No JQuery needed, comma seperation or JSON.

提交回复
热议问题