0

i searched around stackoverflow and found out that cookie only can store string not array.

i have an array like this:

  var myvar = {
   'comment' : '123',
   'blog' : 'blog',
   'test' : '321
  }

Then i use this jquery plugin to manage the cookies: https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js

I use the below code to store the cookie named 'setting':

  $.cookie('setting',  myvar , { expires: 1, path: '/' });

However how do i convert that array into a string , i know i can use .join , but what if my array values for example comment , is a special character like Chinese characters etc.

and how can i access the cookie again and get the string out and convert it again into an array?

sm21guy
  • 626
  • 3
  • 13
  • 33
  • That's an object (not an array). I'd suggest taking a look at this question/answer: http://stackoverflow.com/questions/6810084/encoding-javascript-object-to-json-string , it might help. – David Thomas Oct 07 '12 at 04:35

1 Answers1

2

To store an object in a cookie:

var myvar = {
   'comment' : '123',
   'blog' : 'blog',
   'test' : '321'
};

var serialized = JSON.stringify(myvar);

$.cookie('setting', serialized, { expires: 1, path: '/' });

To retrieve an object from a cookie :

JSON.parse($.cookie("setting"));

See this answer for examples of JSON.stringify and JSON.parse.

Community
  • 1
  • 1
Raine Revere
  • 30,985
  • 5
  • 40
  • 52