将JS对象数组存储在cookie中,没有插件? [英] Store JS object array in a cookie, without plugins?

查看:170
本文介绍了将JS对象数组存储在cookie中,没有插件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是最好的存储方式:

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

在稍后检索的Cookie中?

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!

同时,我想避免jQuery cookie插件,如果可能 - 我在移动工作,每个额外的文件调用是一个性能命中。

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 performance hit.

谢谢!

推荐答案

href =https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify> JSON.stringify

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}]"

数组被转换为JSON格式的字符串,然后您可以将其用作cookie的值。您可以使用 JSON.parse

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.

这篇关于将JS对象数组存储在cookie中,没有插件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆