页面刷新后Cookie中购物车数据丢失的技术求助
未登录状态下将购物车数据存入Cookie,添加数据功能正常,控制台能看到数据已保存,但通过location.reload()或F5刷新页面后,Cookie中的购物车数据会消失。
用户提供的代码如下:
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=/" }
现象
- 页面刷新前控制台输出:
cart: {1: {quantity: 2}, 4: {quantity: 4}} - 页面刷新后控制台输出:
cart: {}
问题原因
getCookie函数存在语法错误:cookiePair[0].trim是引用trim方法本身,而非调用该方法去除Cookie名称前后的空格。这导致Cookie名称匹配失败,getCookie('cart')始终返回null。
后续代码中,JSON.parse(null)得到null,而宽松相等null == undefined结果为true,因此每次刷新页面都会执行cart = {}并重新设置空的购物车Cookie,直接覆盖之前保存的数据。
修复方案
将getCookie函数中的cookiePair[0].trim改为cookiePair[0].trim(),正确调用trim方法去除空格:
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("=") // 调用trim方法去除Cookie名称前后的空格 if(name == cookiePair[0].trim()){ //decode the cookie item and return return decodeURIComponent(cookiePair[1]); } } // Return null if not found return null; }
额外建议
如果希望购物车数据在浏览器关闭后仍能保留,可以为Cookie添加过期时间,例如设置7天有效期:
// 设置Cookie时添加expires参数 const expires = new Date(); expires.setDate(expires.getDate() + 7); document.cookie = `cart=${JSON.stringify(cart)};path=/;expires=${expires.toUTCString()}`;
内容的提问来源于stack exchange,提问作者Eric movchan
相关产品推荐
相关产品推荐

