sm21guy
sm21guy

Reputation: 626

storing javascript array with special characters inside a cookie

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?

Upvotes: 0

Views: 2019

Answers (1)

Raine Revere
Raine Revere

Reputation: 33637

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.

Upvotes: 3

Related Questions