【问题标题】:Woocommerce ajax remove from cartWoocommerce ajax 从购物车中删除
【发布时间】:2017-01-29 12:19:46
【问题描述】:

我意识到有重复的线程,但提出的解决方案不起作用 (100%) - 这是我正在使用的解决方案 https://stackoverflow.com/a/24027583/1826992。基本上,ajax 调用正在从购物车中删除商品,但在我刷新页面之前迷你购物车不会更新。这是我所在的位置:

add_action( 'wp_footer', 'add_js_to_wp_wcommerce');

function add_js_to_wp_wcommerce(){ ?>
    <script type="text/javascript">
    jQuery('body').on('click',".remove",function (){
        var product_id = jQuery(this).attr("data-product_id");
                console.log(product_id);
        jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            url: "/wp-admin/admin-ajax.php",
            data: { action: "product_remove", 
                    product_id: product_id
            },success: function(data){
                console.log(data);
            }
        });

        return false;
    });
    </script>
<?php }



add_action( 'wp_ajax_product_remove', 'product_remove' );
add_action( 'wp_ajax_nopriv_product_remove', 'product_remove' );
function product_remove() {
    $cart = WC()->instance()->cart;
    $id = $_POST['product_id'];
    $cart_id = $cart->generate_cart_id($id);
    $cart_item_id = $cart->find_product_in_cart($cart_id);

    if($cart_item_id){
       $cart->set_quantity($cart_item_id,0);
    }
}

正如我所提到的,这一切似乎都在起作用,直到“行动”。此时的 Console.log(data) 仅带有“0”。我认为这应该有 product_id。

提前感谢您的帮助。

【问题讨论】:

    标签: php jquery ajax wordpress woocommerce


    【解决方案1】:

    从您的 php 函数中返回一些内容并在返回后使用wp_die(),并将您的 js 包装在文档就绪语句中

    【讨论】:

    • 我已经实现了这些更改。关于退货有什么建议吗?我已退回 $cart,但在我重新加载页面之前,没有购物车仍未刷新。谢谢。
    • 您需要返回更新后的购物车,或者只是返回购物车已更新的消息,基于您更新了页面上的购物车列表
    • 你知道如何更新购物车列表吗?对不起,我在这方面有点挣扎。提前致谢。
    • @eluribusunum 从 ajax 返回添加的元素并使用 html 构建列表项,然后将其附加到当前列表中
    猜你喜欢
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    相关资源
    最近更新 更多