javascript 如何使用 localStorage 存储一个简单的购物车?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23554456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I store a simple cart using localStorage?
提问by alimac83
I'm trying to create a javascript cart for a prototype project I'm working on. I realise that in this situation an MVC framework like Angular/Knockout etc would be absolute perfect but I'm still learning how to use those so I can't use them for this particular project. I also realise I could maintain the cart server-side but that's not an option in this scenario.
我正在尝试为我正在处理的原型项目创建一个 javascript 购物车。我意识到在这种情况下,像 Angular/Knockout 等 MVC 框架绝对是完美的,但我仍在学习如何使用它们,所以我不能将它们用于这个特定项目。我也意识到我可以维护购物车服务器端,但在这种情况下这不是一个选项。
At the moment I have a list of html products like so:
目前我有一个 html 产品列表,如下所示:
<ul id="products">
<li data-id="1" data-name="Product 1" data-price="10.00">
<input type="text" /><br />
<button>Add to cart</button>
</li>
<li data-id="2" data-name="Product 2" data-price="15.00">
<input type="text" /><br />
<button>Add to cart</button>
</li>
<li data-id="3" data-name="Product 3" data-price="20.00">
<input type="text" /><br />
<button>Add to cart</button>
</li>
</ul>
On page load I create an empty 'cart' object in localStorage like so:
在页面加载时,我在 localStorage 中创建一个空的“购物车”对象,如下所示:
var cart = {};
cart.products = [];
localStorage.setItem('cart', JSON.stringify(cart));
I've then bound to the click event of the button element as so:
然后我绑定到按钮元素的点击事件,如下所示:
$('button').on('click', function(e) {
var product = $(this).parent();
var quantity = $(product).find('input[type=text]').val();
// Ensure a valid quantity has been entered
if (!isValidInteger(quantity) === true) {
alert('Please enter a valid quantity');
return;
}
product.id = $(product).attr('data-id');
product.name = $(product).attr('data-name');
product.price = $(product).attr('data-price');
product.quantity = quantity;
addToCart(product);
});
I've then written an addToCart() function that should take this product and try to push it into the 'products' array that's a property of 'cart':
然后我编写了一个 addToCart() 函数,它应该接受这个产品并尝试将它推送到作为 'cart' 属性的 'products' 数组中:
function addToCart(product) {
// Retrieve the cart object from local storage
if (localStorage && localStorage.getItem('cart')) {
var cart = JSON.parse(localStorage.getItem('cart'));
cart.products.push(product);
localStorage.setItem('cart', JSON.stringify(cart));
}
}
This isn't working and I'm getting an error:
这不起作用,我收到一个错误:
Uncaught TypeError: Converting circular structure to JSON
I don't understand where I'm going wrong, is anyone able to help?
我不明白我哪里出错了,有人能帮忙吗?
Also once this is resolved, I'm a little confused as to how I'm to maintain the state of the cart. I was hoping I could store all the data in the 'cart' object in localStorage by storing the product ids, names, prices and quantities and then reflecting this in a 'cart' div within the html. If items are added/removed, I'll update the 'cart' object in local storage and then reflect the changes within the html.
此外,一旦解决了这个问题,我对如何维护购物车的状态感到有些困惑。我希望通过存储产品 ID、名称、价格和数量,然后将其反映在 html 中的“购物车”div 中,我可以将所有数据存储在 localStorage 的“购物车”对象中。如果添加/删除项目,我将更新本地存储中的“购物车”对象,然后在 html 中反映更改。
Is there a simpler way to do this? I could really use some pointing in the right direction.
有没有更简单的方法来做到这一点?我真的可以用一些指向正确的方向。
Once again I realise that using Angular or even maintaining the state server-side would be an optimal solution but for this project I'm only able to use jquery/javascript so I need to work within my boundaries.
我再次意识到使用 Angular 甚至维护状态服务器端将是一个最佳解决方案,但对于这个项目,我只能使用 jquery/javascript,所以我需要在我的范围内工作。
Thanks!
谢谢!
回答by zgood
You should declare a separate object for your product item.
您应该为您的产品项目声明一个单独的对象。
$('button').on('click', function(e) {
var li = $(this).parent();
var quantity = $(li).find('input[type=text]').val();
// Ensure a valid quantity has been entered
if (!isValidInteger(quantity) === true) {
alert('Please enter a valid quantity');
return;
}
var product = {};
product.id = $(li).attr('data-id');
product.name = $(li).attr('data-name');
product.price = $(li).attr('data-price');
product.quantity = quantity;
addToCart(product);
});
回答by Musa
Rendering process of Products from Server.
从服务器渲染产品的过程。
function productSocket(doneFn,params){
$.ajax({
type:'GET',
url: "http://localhost:8080/"+params,
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(doneFn)
.fail(function(err){
console.log("AJAX failed: " + JSON.stringify(err, null, 2));
});
}
function productDoneFn(data){
console.log("Okey done"+JSON.stringify(data));
var productContainer=$('#productContainer');
productContainer.empty();
var productContent="";
$.each(data ,function(i,e){
productContent+='<div class="col-md-4 col-sm-6">'+
'<div class="pr">'+
'<div class="pr-img-div">'+
'<a href="detail.html#store/public/parent/detail/'+e.id+'">'+
'<img src="../fs/main/'+e.image+'" alt="" class="img-responsive">'+
'</a>'+
'</div>'+
'<div class="pr-text">'+
'<h3><a href="detail.html#store/public/parent/detail/'+e.id+'">'+e.nameEn+'</a></h3>'+
'<p class="price">$'+e.price+'</p>'+
'<p class="buttons">'+
'<a href="detail.html#store/public/parent/detail/'+e.id+'" class="btn btn-default">View detail</a>'+
'<a href="#" cartBtn pr_id='+e.id+' pr_name_en="'+e.nameEn+'" pr_price="'+e.price+'" pr_image="'+e.image+
'" class="btn btn-primary"><i class="fa fa-shopping-cart"></i>Add to cart</a>'+
'</p>'+
'</div>'+
'</div>'+
'</div>';
});
productContainer.html(productContent);
}
Here is an element like button for adding an item to the Cart and appropriate attributes for saving in Web Storage like localStorage.
这是一个类似按钮的元素,用于将项目添加到购物车,以及用于保存在 Web 存储(如 localStorage)中的适当属性。
var productArray=[];
$(document).on('click','[cartBtn]',function(e){
e.preventDefault();
$(this).html('<i class="fa fa-check"></i>Added to cart');
console.log('Item added ');
var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image')};
if(localStorage.getObj('product')!==null){
productArray=localStorage.getObj('product');
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
else{
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
});
Storage.prototype.setObj = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObj = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
After adding JSON object to Array the result is (in LocalStorage):
将 JSON 对象添加到 Array 后,结果是(在 LocalStorage 中):
[{"id":"99","nameEn":"Product Name1","price":"767","image":"1462012597217.jpeg"},
{"id":"93","nameEn":"Product Name2","price":"76","image":"1461449637106.jpeg"},
{"id":"94","nameEn":"Product Name3","price":"87","image":"1461449679506.jpeg"}]
After this action you can easily send data to server as List in Java.
执行此操作后,您可以轻松地将数据作为 Java 中的列表发送到服务器。