javascript - 添加产品后更新 Woocommerce 购物车 (jQuery)

标签 javascript jquery woocommerce

Ajax 似乎工作正常,但购物车内容不会按预期刷新。单击“添加到购物车”按钮后,我希望刷新购物车的内容。 就像现在一样,我必须手动刷新页面才能看到添加的产品。

我正在使用此功能将产品添加到我的 woocommerce 购物车:

      function addToCart(p_id) {
            jQuery.ajax({
              type: 'POST',
              url: '/wp/?post_type=product&add-to-cart='+p_id,
              data: { 'product_id':  p_id,
              'quantity': amount},
              success: function(response, textStatus, jqXHR){
                    console.log("Product added");
                }/*,
              dataType: 'JSON'*/
            }); 
      }

    jQuery('#addToCart').click(function(e) {
      e.preventDefault();
      addToCart(prod_id["product_id"]);
      return false;
    });  

是否可以在添加产品后仅刷新购物车?

最佳答案

这是可能的 - 您需要使用此代码的修改版本:

http://docs.woothemes.com/document/show-cart-contents-total/

编辑 - 以防将来出现 404

<a class="cart-customlocation" href="<?php echo wc_get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php echo sprintf ( _n( '%d item', '%d items', WC()->cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?> - <?php echo WC()->cart->get_cart_total(); ?></a>

// Ensure cart contents update when products are added to the cart via AJAX (place the following in functions.php).
// Used in conjunction with https://gist.github.com/DanielSantoro/1d0dc206e242239624eb71b2636ab148
add_filter('add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment');

function woocommerce_header_add_to_cart_fragment( $fragments ) {
    global $woocommerce;

    ob_start();

    ?>
    <a class="cart-customlocation" href="<?php echo $woocommerce->cart->get_cart_url(); ?>" title="<?php _e('View your shopping cart', 'woothemes'); ?>"><?php echo sprintf(_n('%d item', '%d items', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count);?> - <?php echo $woocommerce->cart->get_cart_total(); ?></a>
    <?php

    $fragments['a.cart-customlocation'] = ob_get_clean();

    return $fragments;

}

关于javascript - 添加产品后更新 Woocommerce 购物车 (jQuery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13930421/

相关文章:

php - 按销售对产品进行排序 - woocommerce

php - 在WooCommerce中更改股票电子邮件通知收件人

javascript - 如何在 Angular 5 中对加载的 HTML 添加指令?

javascript - 在页面加载时提醒/显示消息 1 次,而不是单击按钮

具有动态字段的 JavaScript 数学

php - 使用 jquery/ajax 插入 MYSQL DB 500 内部服务器错误

php - 将产品自定义字段添加到 WooCommerce 中的管理产品批量编辑表单

javascript - 如何滚动到 asyncData 之后的元素?

javascript - 如何将 JSON 发送到我的 python 脚本?

javascript - 在 Vue 应用程序中导入脚本后 undefined variable