简体   繁体   中英

how could I can I read an array I save in a cookie with jquery.cookie?

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

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'));

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM