Storing a multidimensional array in a cookie?
Today I have a Ajax solution where the server keep开发者_StackOverflow中文版s track of selections are doing and updates the page. I'm redoing this so it will be all done with javascript on the client until the user actually submit the data, performance where quite bad under load with the old solution. (C#, ASP.NET 4.0)
Found a nice way of storing an Array by first serialize it with json link text
Say I have an array like this: {Id, Value}
Any advise how I can store several of the arrays above to a cookie?
Say I have an array like this: {Id, Value}
That's not an array. That's an object. You can multiple copies of those in an array:
[
{"foo": "bar"},
{"foo": "baz"},
{"foo": "boom"}
]
That's a valid JSON string for an array containing objects —in this case, objects with a single property, foo
, each of which has its own value, but the objects don't have to have the same properties, and they can have multiple properties. For instance:
[
{},
["zero", "one", "two", "three"],
"I'm just a string",
{
"f0": "foo zero",
"f1": "foo one",
"f2": "foo two",
"all": ["foo zero", "foo one", "foo two"]
},
42
]
That's a valid JSON string for an array with five entries:
- An object with no properties (e.g., a "blank" object).
- An array with four entries.
- A string.
- An object with four properties:
f0
,f1
,f2
, andall
.f0
,f1
, andf2
all have string values;all
has an array of strings as a value. - The answer to Life, The Universe, and Everything.
You can turn an object or array into a valid JSON string (stringify), and reverse the process (parse) client-side using any of several libraries. Crockford (the inventer of JSON) has several on his github page, most notably json2.js although json2.js relies on eval
for parsing; since that's not really ideal you can use json_parse.js
(a recursive descent parser that doesn't use eval
) or json_parse_state.js
(a state machine that doesn't use eval
) instead.
Use JSON.stringify
to generate a string from the array object.
http://msdn.microsoft.com/en-us/library/cc836459(v=vs.85).aspx
Cookies only store simple strings. You can come up with you own system something like this:
$content = [id,value];[text,textvalue];
setcookie("Array", $content);
When you want it back, you explode the string at delimiters (in this case ';' and ',')
Converting an array into a string:
> JSON.stringify([1, 2])
*returns* '[1, 2]'
We can then make it a cookie:
> $.cookie('cookie', '[1, 2]')
And then parse it:
> JSON.parse($.cookie('cookie'))
*returns* [1, 2]
精彩评论