如何用javascript / jquery编码cookie? [英] How to encode cookie with javascript/jquery?

查看:128
本文介绍了如何用javascript / jquery编码cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我必须读取cookie并获得值cart回来用javascript和打印它在HTML文档,但我没有想法如何使用它,你能帮助我吗?我以前从来没有使用过cookies或JSON,但我认为应该用JSON,你能解释一下它是如何工作的吗?



console.log(document.cookie);



我收到类似这样的: cart =%7B%22items%22%3A%7B%228%22%3A1%7D%7D; p>

我不知道如何编码它。



谢谢

解决方案

这是等价于 {items:{8:1}}的URL编码



所有你需要做的是解码和解析JSON:

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

然后,日志记录器应该给你一个带有'items'属性的对象,你可以根据需要访问。



编辑:



下面是一个遍历项目的方法,项目及其总数量。

  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 Quantity:+ quantity_total);


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

解决方案

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

这篇关于如何用javascript / jquery编码cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆