简体   繁体   English

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

[英]How to encode cookie with javascript/jquery?

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.他用 PHP 为我设置了一个 cookie,其中包含添加到购物车的产品数量。 The cookie is called "cart", and the variable with the amount of the products is called "items". 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?我必须读取cookie并使用javascript获取“cart”的值并将其打印在HTML文档中,但我不知道如何使用它,你能帮我吗? 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 或 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谢谢

That is the URL encoded equivalent of {"items":{"8":1}} which is the JSON string you want.那是{"items":{"8":1}}的 URL 编码等价物,它是您想要的 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);

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}};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM