jQuery arrays into cookie

孤者浪人 提交于 2019-12-24 12:02:14

问题


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 "[]"
$.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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6426033/jquery-arrays-into-cookie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!