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

Shopify购物车仅硬编码值可更新,动态取值触发404错误求助

问题描述

我编写了一段代码,用于在购物车金额超过固定阈值时为客户添加免费商品。这些配置值(免费商品ID、价格阈值)计划通过主题设置动态获取,但目前代码仅在使用硬编码值时生效,使用动态取值时会触发cart/update.js文件的404错误。


可用代码(硬编码值)

$.ajax({
    type: 'get',
    url: '/cart.js',
    dataType: 'json',
    success: function(data) {
        var total_cart_price = 0;
        total_cart_price = data.total_price / 100;
        var free_product_id = settings.first_free_product;
        var first_free_price_threshold = settings.first_free_price_threshold;
        console.log(`Free product ID: ${free_product_id} and price threshold: ${first_free_price_threshold}`);

        const cartItems = data.items.map(item => item.id);
        let updates = {};
        if (total_cart_price < 60) {
            updates = {
                48270424670533: 0
            };
        }
        if (total_cart_price >= 60) {
            updates = {
                48270424670533: 1
            };
        }
        fetch(window.Shopify.routes.root + 'cart/update.js', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                updates
            })
        }).then(response => {
            myCartRefresher();
            return response.json();
        }).catch((error) => {
            console.error('Error:', error);
        });
    }
});

不可用代码(动态取值)

$.ajax({
    type: 'get',
    url: '/cart.js',
    dataType: 'json',
    success: function(data) {
        var total_cart_price = 0;
        total_cart_price = data.total_price / 100;
        var free_product_id = {{ settings.first_free_product }};
        var first_free_price_threshold = {{ settings.first_free_price_threshold }};
        console.log(`Free product ID: ${free_product_id} and price threshold: ${first_free_price_threshold}`);

        const cartItems = data.items.map(item => item.id);
        let updates = {};
        if (total_cart_price < first_free_price_threshold) {
            updates = {
                free_product_id: 0
            };
        }

        if (total_cart_price >= first_free_price_threshold) {
            updates = {
                free_product_id: 1
            };
        }
        fetch(window.Shopify.routes.root + 'cart/update.js', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                updates
            })
        }).then(response => {
            myCartRefresher();
            return response.json();
        }).catch((error) => {
            console.error('Error:', error);
        });
    }
});

错误原因分析

  1. 动态对象属性名使用错误:在不可用代码中,直接以free_product_id: 0的方式定义对象属性时,free_product_id会被当作字符串字面量作为键名,而非变量存储的实际商品ID。Shopify的cart/update.js接口需要真实商品ID作为键来更新购物车,用字面量"free_product_id"作为ID请求自然会返回404。
  2. Liquid变量类型问题:{{ settings.first_free_product }}输出的内容默认是字符串类型,而购物车更新接口需要数字类型的商品ID,类型不匹配也可能导致请求异常。

修正后的代码

$.ajax({
    type: 'get',
    url: '/cart.js',
    dataType: 'json',
    success: function(data) {
        var total_cart_price = data.total_price / 100;
        // 将Liquid输出的变量转换为数字类型,确保ID和阈值为数值
        var free_product_id = Number({{ settings.first_free_product }});
        var first_free_price_threshold = Number({{ settings.first_free_price_threshold }});
        console.log(`Free product ID: ${free_product_id} and price threshold: ${first_free_price_threshold}`);

        const cartItems = data.items.map(item => item.id);
        let updates = {};
        
        // 使用方括号语法动态设置对象属性名,把变量值作为键
        if (total_cart_price < first_free_price_threshold) {
            updates[free_product_id] = 0;
        } else if (total_cart_price >= first_free_price_threshold) {
            updates[free_product_id] = 1;
        }
        
        fetch(window.Shopify.routes.root + 'cart/update.js', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                updates
            })
        }).then(response => {
            myCartRefresher();
            return response.json();
        }).catch((error) => {
            console.error('Error:', error);
        });
    }
});

关键修正点

  • 动态对象键赋值:使用updates[free_product_id] = 0替代字面量属性定义,确保变量存储的真实商品ID被用作请求参数的键。
  • 类型转换:通过Number()将Liquid输出的字符串转换为数字类型,避免类型不匹配导致的接口错误。
  • 逻辑优化:将两个独立if改为if-else结构,避免重复赋值,提高代码效率。

内容的提问来源于stack exchange,提问作者Real Noob

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 00:10:55