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

点击加入购物车按钮未校验登录,需实现未登录跳转登录页

解决未登录仍可添加商品至购物车的问题

需求与问题

  • 需求:点击**Add to cart(加入购物车)**按钮时,需先校验用户是否登录:已登录则执行购物车添加逻辑,未登录则跳转至登录页。
  • 当前问题:现有代码未做登录校验,未登录用户也能直接添加商品到购物车。

修改后的代码

$('.divpr').on('click', 'button.cart', function () {
    // 校验用户登录状态,此处需根据实际项目的登录标识调整
    // 示例:假设登录状态存在localStorage的isLoggedIn字段中,值为true表示已登录
    const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
    
    if (!isLoggedIn) {
        // 未登录则跳转至登录页,替换为你的登录页实际URL
        window.location.href = '/login';
        return; // 阻止后续购物车逻辑执行
    }

    var idstr = this.id.toString();
    // 确保cart变量已初始化,避免未定义报错
    let cart = JSON.parse(localStorage.getItem('cart')) || {};
    
    if (cart[idstr] != undefined) {
        console.log("exist");
        cart[idstr][0] = cart[idstr][0] + 1;
        cart[idstr][4] = cart[idstr][4] + cart[idstr][3];
        localStorage.setItem('cart', JSON.stringify(cart));
    } else {
        const qty = 1;
        const price = document.getElementById('price' + idstr).innerHTML;
        const totalPrice = document.getElementById('price' + idstr).innerHTML;
        const image = document.getElementById('img' + idstr).src;
        const aname = document.getElementById('name' + idstr).innerHTML;
        console.log("not");
        cart[idstr] = [qty, aname, image, parseInt(price), parseInt(totalPrice)];
        localStorage.setItem('cart', JSON.stringify(cart));
    }
    
    console.log(cart);
});

关键改动说明

  • 登录校验逻辑:在执行购物车操作前,先判断用户登录状态。示例中用localStorage.getItem('isLoggedIn')做校验,实际项目中可能需要对接后端接口验证、读取登录cookie或其他业务标识,需根据实际情况调整。
  • 未登录拦截跳转:如果检测到未登录,直接跳转至登录页,并通过return终止后续购物车代码执行,避免未授权操作。
  • cart变量初始化:添加let cart = JSON.parse(localStorage.getItem('cart')) || {},避免因cart未定义导致的代码报错。
  • 变量声明优化:将qty、price等变量改为const(值无需修改时),提升代码规范性。

内容的提问来源于stack exchange,提问作者muneeb rehman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 21:10:20