How to encode cookie with javascript/jquery?

前端 未结 2 1690
一整个雨季
一整个雨季 2020-12-18 06:50

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

相关标签:
2条回答
  • 2020-12-18 07:14

    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);
    
    0 讨论(0)
  • 2020-12-18 07:14

    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 讨论(0)
提交回复
热议问题