You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

页面刷新后Cookie中购物车数据丢失的技术求助

购物车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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 14:35:16