开发者

jQuery arrays into cookie

开发者 https://www.devze.com 2023-03-14 05:03 出处:网络
var adddata = []; adddata[ group ] = []; adddata[ group ][ id ] = option; // option is an object like { foo : \'bar\' }
var adddata = [];
adddata[ group ] = [];
adddata[ group ][ id ] = option; // option is an object like { foo : 'bar' }

console.log( adddata ); // looks ok

$.cookie( 'cookiename', JSON.stringify( adddata ) );
console.log( $.cookie( 'cookiename' ) ); // just "[]"
$开发者_JAVA百科.cookie( 'cookiename', adddata );
console.log( $.cookie( 'cookiename' ) ); // "an empty string"

// in another file
var cdata = JSON.parse( $.cookie( 'cookiename' ) );
$.each( cdata, function( group, items ){
    /* and so on */
});

As you can see, I use the $.cookie plugin. But how can I store arrays into the cookie the right way?

Thanks & regards, Alex


If group and id are not numeric values, JSON.stringify will ignore them. Only numeric properties are taken into account when converting an array to JSON.

See:

> a = []
  []
> a['foo'] = 5
  5
> a[0] = 42
  42
> JSON.stringify(a)
  "[42]"

You have to use an object {} if you deal with non-numerical properties:

> a = {}
  Object
> a['foo'] = 5
  5
> JSON.stringify(a)
  "{"foo":5}"

Never use a JavaScript array as associative array. JS arrays should only have numerical keys. For everything else, use plain objects.


Serialization is required before storage since a cookie can only be a string. However, there are JS/jQ cookie libraries available which attempt to transparently handle the un/serialization for you. The most popular cookie library which people use with jQuery (the one you are using) does not attempt to handle this for you, so your extra step is required.

Edit: Ah, I missed part of the question regarding the serialization not resulting in the correct value. See Felix Kling's answer, it is correct.

0

精彩评论

暂无评论...
验证码 换一张
取 消