首页 > 解决方案 > 如何在 Spring Boot 中为登录用户合并存储在本地存储中的购物车项目?

问题描述

我正在使用 Spring Boot 开发在线购物网络应用程序。我为用户添加了添加到购物车功能,这样每当他们访问应用程序时,他们就可以将他们选择的项目添加到购物车中。

为了在购物车中添加商品,我在 JavaScript 中使用了 localStorage。所以我有一个困惑,当用户在结帐前成功登录到应用程序时,我需要合并旧购物车。所以我想知道我应该如何在我的spring boot应用程序中实现这个东西。

下面是我将商品添加到购物车的脚本,其中我将类别、产品 ID、产品名称、价格、数量和产品图片存储到 localStorage。

    function addtocart(productid, productname) {
                var category = document.getElementById('category').value;
                var productimage = document.getElementById("pimage").src; 
                var quantity = $("#quantity").val() != "" ? parseInt($("#quantity").val()) : 0;
                var price = $("#pprice").text();
                var pprice = price.replace(/[^\x00-\x7F]/g, "");
                var cart = localStorage.getItem("cart");
                var pcart = JSON.parse(cart) != null ? JSON.parse(cart) : [];
                var list = pcart;
                var present_or_not = pcart.findIndex(item => item.productid == productid);
                if (cart == null || present_or_not == null || present_or_not == -1) {
                        var product = {
                          productid: productid,
                          productname: productname,
                          pprice: pprice,
                          quantity: quantity,
                          productimage : productimage,
                          category : category,
                    };
                    pcart.push(product);
                    localStorage.setItem("cart", JSON.stringify(pcart));
                    swal({title: "Item Added", text: "Item added to cart", type: "success"},
                            function(){
                        location.reload();
                       })
                  } else {
                    var actual_stored_product = pcart[present_or_not];
                    pcart.splice(present_or_not, 1);  
                    var actual_qty = actual_stored_product.quantity == null || actual_stored_product.quantity == "" ? 0 : actual_stored_product.quantity;
                    var actual_price = actual_stored_product.pprice == null || actual_stored_product.pprice == "" ? 0 : actual_stored_product.pprice;
                    actual_stored_product.quantity = parseInt(actual_qty) + quantity ;
                    actual_stored_product.pprice = parseFloat(actual_price)+parseFloat(pprice);
                    pcart.push(actual_stored_product);
                    localStorage.setItem("cart", JSON.stringify(pcart));
                    swal({title: "Item Quantity Increased", text: "Item Quantity Updated of: "+productid, type: "success"},
                            function(){
                        location.reload();
                       })
                  }
    }

我应该如何知道一个用户可以拥有多个购物车或多个用户拥有一个购物车?

请通过提出解决方案来帮助我。

标签: javascriptspring-bootjsplocal-storageshopping-cart

解决方案


推荐阅读