简体   繁体   中英

Implement shopping cart JavaScript

here what I am trying to do is when a user clicks the + button function should get called, it looks for the cookie shopping_cart. Then it tries to find the JSON with key 'item_qty', which is key-value pair of all the items in the cart. But the cart is not updating, moreover when clicked on + button is showing Unexpected token N in JSON at position 0

In browser console I am getting it as

"csrftoken=some_value; shopping_cart=None"

var updateCart = function (count) {
    $('#cart-info').val($('#cart-info').val() + count);
};



var item_add = function (item_slug) {
    var shopping_cart = JSON.parse($.cookie("shopping_cart"));
    var item_slug = item_slug;
    if(shopping_cart.hasOwnProperty('item_qty')){
        item_qty_dict = shopping_cart['item_qty'];
        if(item_qty_dict.hasOwnProperty(item_slug)){
            var count_pre = item_qty_dict[item_slug];
            item_qty_dict[item_slug] = count_pre + 1;
        }
        else {
            item_qty_dict[item_slug] = 1;
            shopping_cart['item_qty'] = item_qty_dict;
        }
    }
    else {
        shopping_cart = {}
        shopping_cart['item_qty'] = {item_slug: 1};
    }
    $.cookie("shopping_cart", JSON.stringify(shopping_cart));
    var temp= $.cookie('shopping_cart')
    console.log(JSON.parse(temp));
};


var buttonPlus = $(".cart-qty-plus");

var incrementPlus = buttonPlus.click(function () {
    var $n = $(this)
        .parent(".qnty_chngr")
        .find(".qty");
    $n.val(Number($n.val()) + 1);
    var product_slug = $(this).parent(".qnty_chngr").siblings('.product-slug').val();
    console.log(product_slug);
    updateCart(1);
    item_add(product_slug);
});

HTML:

                        <div class="qnty_chngr">
                                    <button class="cart-qty-plus" type="button" value="+">+</button>
                                    <input type="text" name="qty" maxlength="12" value="1" class="input-text qty"/>
                                    <button class="cart-qty-minus" type="button" value="-" title="Add less quantity">-</button>
                        </div>
                        <input type="hidden" class="product-slug" name="product_slug" value="{{ medicine.slug }}">
                        <div class="add_to_cart">
                            <button  class="add_to_cart_txt" value="10"><span class="AddInfoBtn">Add </span></button>

                        </div>,

Seems in your cookie there is no valid JSON. None is not valid, it should be "None" (with quotes). Remove the cookie before testing.

Also if possible try using this library which works the way you expected.

https://github.com/js-cookie/js-cookie

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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