javascript 在 cookie 中存储和检索 json 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5501968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:25:04  来源:igfitidea点击:

storing and retrieving json objects to / from a cookie

javascriptjsoncookies

提问by richzilla

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

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

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 $.parseJSONand evalfail when i attempt to read the objects back from the cookie. Any help would be appreciated.

然后我将这个对象保存在我的 cookie 中。随着更多产品的添加(它是一个购物篮),我通过将新对象附加到 cookie 字符串的末尾来添加更多字符串(因此我基本上有很多小的单独对象)。不过,我无法将对象从 cookie 字符串中取出。双方$.parseJSONeval当我尝试读取对象从cookie回失败。任何帮助,将不胜感激。

回答by Matthew Flaschen

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.

所述[]表示的阵列。当你想添加另一个产品时,你从 cookie 中加载它,更新数组,然后再次保存它。如果你愿意,你可以跳过外部对象,让 cookie 只是数组。

EDIT: Say cookieStris your cookie.

编辑:说cookieStr是你的饼干。

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

回答by Eyal Ch

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.

将 JSON.stringify(cookieStr) 返回的值保存到 cookie 不是一个好习惯。它可能会导致某些浏览器出现错误。

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

在使用它之前,您应该将其转换为 base64(使用 btoa),并且在读取它时,从 base64 转换(使用 atob)

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

write_cookie(val)