簡體   English   中英

實施購物車JavaScript

[英]Implement shopping cart JavaScript

在這里,我試圖做的是當用戶單擊+按鈕函數時,它將查找cookie shopping_cart。 然后,它嘗試查找具有鍵“ item_qty”的JSON,該鍵是購物車中所有商品的鍵值對。 但是購物車沒有更新,此外,當單擊+按鈕時,在位置0的JSON中顯示意外令牌N

在瀏覽器控制台中,我得到它

“ 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>,

您的Cookie中似乎沒有有效的JSON。 None無效,應為"None" (帶引號)。 在測試之前刪除cookie。

另外,如果可能,請嘗試使用符合您預期方式的該庫。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM