我想做的是在用户未登录时将数据保存到cookie中一切工作正常,我看到数据保存,但当我刷新页面使用location.reload()或者按F5键,数据就会消失。
on my main.html
function getCookie(name){
var cookieArr = document.cookie.split(";")
//loop through the array of elements
for(var i = 0; i < cookieArr.length; i++){
var cookiePair = cookieArr[i].split("=")
if(name == cookiePair[0].trim){
//decode the cookie item and return
return decodeURIComponent(cookiePair[1]);
}
}
// Return null if not found
return null;
}
// Set a Cookie
var cart = JSON.parse(getCookie('cart'))
if(cart == undefined){
cart = {}
document.cookie = 'cart=' + JSON.stringify(cart) + ";path=/";
}
和我的cart.js文件:
function addCookieItem(productId, action){
if(action == 'add'){
if(cart[productId] == undefined){
cart[productId] = {'quantity':1}
}else{
cart[productId]['quantity'] += 1
}
}
if(action == 'remove'){
cart[productId]['quantity'] -= 1
if(cart[productId]['quantity'] <=0){
delete cart[productId]
}
}
console.log('cart:', cart)
document.cookie = 'cart=' + JSON.stringify(cart) + ";path=/"
}
输出示例:{productID, {'quantity':numberOfItems}}
before page reload:购物车:- {1:{quantity: 2}, 4: {quantity: 4}})
页面重载后:车:车- {}
仔细观察第一个if语句的getCookie函数后它应该是:
if(name == cookiePair[0].trim())