Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store an array in a JavaScript cookie?

Does anyone have a piece of JavaScript code that creates a cookie and stores an array in it? If you also have the code to read through through cookie and delete it, that would be great as well. Thanks!

like image 309
Josh Avatar asked Aug 04 '10 18:08

Josh


Video Answer


2 Answers

have a look at: http://plugins.jquery.com/project/cookie https://plugins.jquery.com/cookie/

to store an array

$.cookie('COOKIE_NAME', escape(myarray.join(',')), {expires:1234});

to get it back

cookie=unescape($.cookie('COOKIE_NAME'))
myarray=cookie.split(',')
like image 179
Christian Smorra Avatar answered Oct 03 '22 09:10

Christian Smorra


jQuery, Cookie plugin:
Converting an array into a string:

> JSON.stringify([1, 2]);
> '[1, 2]'

Then:

$.cookie('cookie', '[1, 2]');

And then parse it:

JSON.parse($.cookie('cookie'));
> [1, 2]
like image 28
fzzle Avatar answered Oct 03 '22 11:10

fzzle