最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to encode cookie with javascriptjquery? - Stack Overflow

programmeradmin3浏览0评论

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".

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?

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

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

And I have no idea how to encode it.

Thank you

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".

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?

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

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

And I have no idea how to encode it.

Thank you

Share Improve this question asked Mar 29, 2012 at 15:12 user1247294user1247294 3
  • How was the cookie encoded in PHP? – Bergi Commented Mar 29, 2012 at 15:16
  • That's just URL encoded. – Rory McCrossan Commented Mar 29, 2012 at 15:24
  • 1 You're talking about DEcoding, not ENcoding. Pls change the title. – pythonator Commented Jan 10, 2020 at 14:33
Add a ment  | 

2 Answers 2

Reset to default 12

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

All you have to do is decode it and parse the 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.

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}};
发布评论

评论列表(0)

  1. 暂无评论