What I'm trying to do is save data into a cookie when user is not logged in everything works fine and i see the data save but when i refresh the page using location.reload() or just F5 the data just disappear.
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=/";
}
and on my cart.js file:
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=/"
}
output example: {productID, {'quantity':numberOfItems}}
before page reload: cart: – {1: {quantity: 2}, 4: {quantity: 4}})
after page reload: cart: cart-{}
So after taking a close look in getCookie function on the first if statement it suppose to be:
if(name == cookiePair[0].trim())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.