【发布时间】:2021-07-28 05:20:43
【问题描述】:
我正在使用 Spring Boot 为在线购物网络应用程序实现购物车功能。我使用 localStorage 将用户的购物车项目存储在其中。但问题是,假设我在购物车中存储了一些物品并关闭了我的应用程序和浏览器,第二天我再次打开该应用程序以查看我的购物车物品。但我没有找到任何存放在购物车内的物品。那么,当使用 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();
})
}
}
【问题讨论】:
-
关闭浏览器后清除。
-
@ObsidianAge 我认为她使用的是 localStorage 而不是 sessionStorage。
-
好的,意思是我需要使用 sessionStorage 来存储购物车物品?
-
localStorage数据是特定于域的。abc.com的示例 localStorage 将不同于xyz.com和localStorage如果选项卡以隐身模式或私有模式打开,则数据将被清除,否则localStorage没有到期日期 -
好的,我正在用我已经实现的一些代码更新我的问题。
标签: javascript html jquery local-storage shopping-cart