【问题标题】:Add variable product to cart with Ajax in woocommerce在 woocommerce 中使用 Ajax 将可变产品添加到购物车
【发布时间】:2016-04-29 05:06:14
【问题描述】:

我下面的代码可以工作,除了它不仅将具有所选变体的可变产品添加到购物车中,而且还添加了相同数量的相同产品,没有变体,就好像它是一个简单的产品一样。

element.on('click', 'button[type="submit"]', event => {
    event.preventDefault();

    const quantity = parseInt(element.find('input[name="quantity"]').val(), 10) || 1;
    const addToCartUrl = '/shopping-basket/?wc-ajax=add_to_cart';
    let xWWWFormUrlencodedData = `quantity=${quantity}`;

    switch (scope.singleCopy.type) {
        case 'variable': {
            if (scope.selectedVariation) {
                for (const attr of scope.selectedVariation.attributes) {
                    xWWWFormUrlencodedData += `&attribute_pa_${attr.slug}=${attr.option}`;
                }
                xWWWFormUrlencodedData += `&add-to-cart=${scope.singleCopy.id}`;
                xWWWFormUrlencodedData += `&product_id=${scope.singleCopy.id}`;
                xWWWFormUrlencodedData += `&variation_id=${scope.selectedVariation.id}`;
            }
            break;
        }
        case 'simple': {
            xWWWFormUrlencodedData += `&product_id=${scope.singleCopy.id}`;
            break;
        }
        default: {
            console.error(`Unknown product type ${scope.singleCopy.type}.`); //eslint-disable-line no-console
        }
    }

    $http.post(addToCartUrl, xWWWFormUrlencodedData, {
        withCredentials: true,
        headers: {
            'Cache-Control': 'no-cache',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            Pragma: 'no-cache'
        }
    }).success(result => {
        if (result.error) {
            console.warn('The product has been added to the cart despite that the result object indicates an error!');
            // TODO: handle error
            return;
        }
        console.log('Success.', result);
        $rootScope.$broadcast('/cart/update/add');
    }).catch(data => {
        console.error(data);
        // TODO: handle error
    });

});

如果我不发送product_id,则只会将具有所选变体的可变产品添加到购物车(太棒了!),但结果对象指示错误(没有描述)。如果我然后导航到购物车页面,我会在 ui 中收到另一条错误消息:“抱歉,无法购买此产品。”

我想我现在已经尝试了所有排列,在参数上设置变体 ID 而不是产品 ID,删除和添加参数等等。知道如何解决这个问题吗?

【问题讨论】:

标签: ajax wordpress woocommerce


【解决方案1】:

在与插件作者建立little chat 之后,我设法使用派生自https://stackoverflow.com/a/27278035/601466 的自定义端点完成了我想要的工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    相关资源
    最近更新 更多