Reputation: 5878
I am using jquery.cookie (https://github.com/carhartl/jquery-cookie/tree/v1.4.1) and Ive been having many problems with this, I am trying to save an array of this structure
var obj = {
'row1' : {
'key1' : 'input1',
'key2' : 'inpu2'
},
'row2' : {
'key3' : 'input3',
'key4' : 'input4'
}
};
But when I want to read it I get this
row1%5Bkey1%5D=input1&row1%5Bkey2%5D=inpu2&row2%5Bkey3%5D=input3&row2%5Bkey4%5D=input4
I am sending it at this way:
$.cookie('listresult', $.param(obj), { expires: 10 });
The worst is that sometimes works, and sometimes doesnt, so, I have no idea whats wrong... Any idea how to send and transform the data?
To read it I use this
var cookieValue = $.cookie("listresult");
When I try this... doesnt work
$.parseJSON($.cookie("listresult");)
Thanks
Upvotes: 0
Views: 101
Reputation: 7205
You shouldn't use jquery.param
method. It is intended for use with HTTP (AJAX) requests so that's not your case. You have to use JSON.stringify
on writing cookie and JSON.parse
on reading:
// write (save):
$.cookie('listresult', JSON.stringify(obj), { expires: 10 });
// read (restore):
var obj = JSON.parse($.cookie('listresult'));
Upvotes: 1
Reputation: 64943
If you carefully read jQuery plugin's manual, you'll find this:
json
Turn on automatic storage of JSON objects passed as the cookie value. Assumes JSON.stringify and JSON.parse:
$.cookie.json = true;
This way your JavaScript objects will be serialized to JSON when you set the whole cookie, and they'll get deserialized into a JavaScript again when you retrieve that cookie.
Upvotes: 0