开发者

storing and retrieving json objects to / from a cookie

Im att开发者_如何学Cempting 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
}

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.


its not a good practice to save the value that returned from JSON.stringify(cookieStr) to the cookie. it can lead to a bug in some browsers.

before using it you should convert it to base64 (using btoa), and when reading it, converting from base64 (using atob)

val = JSON.stringify(cookieStr)
val = btoa(val)

write_cookie(val)


It should probably be like:

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

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.

EDIT: Say cookieStr is your cookie.

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜