javascript - 如何在 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();
})
}
}
我应该如何知道一个用户可以拥有多个购物车或多个用户拥有一个购物车?
请通过提出解决方案来帮助我。
解决方案
推荐阅读
- jenkins - 使用 SCM 中的声明性 Jenkins 管道 - Subversion - 如何获取 svn Url?
- node.js - 为什么 axios 尝试连接端口 80 而不是 8080?
- python - 当求解 13 方程线性方程需要太多时,是否意味着规范的一些问题?
- node.js - 使用两组不同的参数运行命令行
- excel - 是否可以在 Excel 中创建一个没有文本的下拉列表,只有颜色选项来填充单元格?
- c++ - 为其他人编译 OpenCV + Gstreamer
- junit - Junit测试后如何回滚Rabbit-mq消息?
- delphi - Delphi 5:将点击事件分配给 TImage 时出错
- c# - 如何将数据从一个视图显示到另一个 ASP.NET CORE 5.0 MVC
- laravel - laravel Eloquent 查询合集再次搜索