如何使用 javascript/jquery 对 cookie 进行编码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9928246/
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-26 08:15:12  来源:igfitidea点击:

How to encode cookie with javascript/jquery?

javascriptjqueryhtmljsoncookies

提问by ms2

I am working on an online shop together with my friend. He set a cookie for me with PHP with the amount of added products to the Cart. The cookie is called "cart", and the variable with the amount of the products is called "items".

我和我的朋友一起在网上商店工作。他用 PHP 为我设置了一个 cookie,其中包含添加到购物车的产品数量。cookie 被称为“cart”,带有产品数量的变量被称为“items”。

And I have to read the cookie and get the value of "cart" back with javascript and print it in the HTML document, but I have no Idea how to use it, can you please help me? I have never worked with cookies or JSON before, but I think it should be done with JSON, can you please explain it to me how it works?

我必须读取cookie并使用javascript获取“cart”的值并将其打印在HTML文档中,但我不知道如何使用它,你能帮我吗?我以前从未使用过 cookie 或 JSON,但我认为应该使用 JSON 来完成,您能向我解释一下它是如何工作的吗?

when I do : console.log(document.cookie);

当我做 : console.log(document.cookie);

I receive something like this: cart=%7B%22items%22%3A%7B%228%22%3A1%7D%7D;

我收到这样的东西: cart=%7B%22items%22%3A%7B%228%22%3A1%7D%7D;

And I have no idea how to encode it.

我不知道如何编码它。

Thank you

谢谢

回答by kiswa

That is the URL encoded equivalent of {"items":{"8":1}}which is the JSON string you want.

那是 URL 编码的等价物,{"items":{"8":1}}它是您想要的 JSON 字符串。

All you have to do is decode it and parse the JSON:

您所要做的就是对其进行解码并解析 JSON:

var cart = JSON.parse(decodeURIComponent(document.cookie.cart));

Then logging cart should give you an object with an 'items' property that you can access as needed.

然后记录购物车应该为您提供一个具有“items”属性的对象,您可以根据需要访问该对象。

EDIT:

编辑:

As an example, here's a way to iterate through the items and determine the total number of items and the total of all their quantities.

例如,这是一种遍历项目并确定项目总数及其所有数量总和的方法。

var items_total = 0,
    quantity_total = 0;
for (var prop in cart.items) {
    items_total += 1;
    quantity_total += cart.items[prop];
}

console.log("Total Items: " + items_total);
console.log("Total Quantities: " + quantity_total);

回答by rgthree

Looks like you just need to decode it, then you will want to parse/eval it to get a workable object:

看起来你只需要解码它,然后你会想要解析/评估它以获得一个可行的对象:

var obj, decoded = decodeURIComponent(document.cookie.cart);
if(window.JSON && JSON.parse){
  obj = JSON.parse(decoded);
} else {
  eval('obj = ' + decoded);
}
// obj == {"items":{"8":1}};