存储和检索json对象到/从cookie [英] storing and retrieving json objects to / from a cookie

查看:249
本文介绍了存储和检索json对象到/从cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在一个cookie存储json对象,但我遇到了几个问题。
我可以这样创建我的对象:

Im attempting to store json objects in a cookie, but im running into a few problems. I can create my object like this:

product = {
   "name" : "prodname",
   "quantity" : 4
}

我的cookie。随着更多的产品添加(它的一个购物篮)我添加更多的字符串通过追加新对象到cookie字符串的结尾(所以我基​​本上有很多小的独立对象)。我有麻烦使对象从cookie字符串退出尽管。当我尝试从cookie中读取对象时, $。parseJSON eval 失败。

i then save this object in my cookie. As more products are added (its a shopping basket) i add further strings by appending new objects onto the end of the cookie string (so i essentially have lots of small seperate objects) . Im having trouble getting the objects back out of the cookie string though. Both $.parseJSON and eval fail when i attempt to read the objects back from the cookie. Any help would be appreciated.

推荐答案

它应该是这样:

{"products": [
    {
       "name" : "prodname",
       "quantity" : 4
    },
    {
       "name" : "prodname2",
       "quantity" : 3
    }
]}

[] 表示数组。当你想添加另一个产品,你从cookie加载它,更新数组,然后再次保存。

The [] signifies an array. When you want add another product, you load it from the cookie, update the array, then save it again. If you wanted, you could skip the outer object and have the cookie just be the array.

编辑:说 cookieStr 是您的Cookie。

Say cookieStr is your cookie.

var root = $.parseJSON(cookieStr);
root.products.push(newProduct);
cookieStr = JSON.stringify(root);

这篇关于存储和检索json对象到/从cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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