Create array in cookie with javascript

后端 未结 9 902
-上瘾入骨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 10:53

    I agree with other comments - you should not be doing this and you should be using JSON. However, to answer your question you could hack this by storing the array as a comma-delimited string. Lets say you wanted to save a the following Javascript array into a cookie:

    var a = ['peter','esther','john'];
    

    You could define a cookie string, then iterate over the array:

    // Create a timestamp in the future for the cookie so it is valid
    var nowPreserve = new Date();
    var oneYear = 365*24*60*60*1000; // one year in milliseconds
    var thenPreserve = nowPreserve.getTime() + oneYear;
    nowPreserve.setTime(thenPreserve);
    var expireTime = nowPreserve.toUTCString();
    
    // Define the cookie id and default string
    var cookieId = 'arrayCookie';
    var cookieStr = '';
    
    // Loop over the array
    for(var i=0;i

    In this example, you would get the following cookie stored (if your domain is www.example.com):

    arrayCookie=peter,ester,john;expires=1365094617464;domain=www.example.com
    

提交回复
热议问题