开发者

Store JS object array in a cookie, without plugins?

What's the best way to store this:

var mydata = [{'11 Alveston Road, Manchester':1},
              {'12 Plymouth Street, Liverpool':2}];

in a cookie to retrieve later?

I can obviously simply turn it all into a text string, and add some symbols as delimiters (hoping that those symbols don't occur anywhere in the data values), but it seems a bit hacky!

Also I'd like to avoid the jQuery cookie plugin etc if possible - I'm working in mobile, and each extra file call is a performa开发者_JS百科nce hit.

Thanks!


This sounds like a job for JSON.stringify:

var myData = JSON.stringify(
    [
        {'11 Alveston Road, Manchester':1},
        {'12 Plymouth Street, Liverpool':2}
    ]
); // "[{"11 Alveston Road, Manchester":1},{"12 Plymouth Street, Liverpool":2}]"

The array is converted into a string in JSON format, which you can then use as the value of your cookie. You can decode it with JSON.parse.


Note: since you are using mobile browsers, they're probably quite modern and so have JSON natively installed. You can use this library to work around this in these cases.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜