【问题标题】:AJAX cart update woocommerceAJAX 购物车更新 woocommerce
【发布时间】:2018-07-29 21:47:32
【问题描述】:

点击“更新购物车”按钮后,如何通过 AJAX 更新购物车内容?

当我尝试使用 $fragments 函数时,它总是返回 true...我尝试使用 woocommerce 挂钩,但字段未通过 AJAX 刷新。我真的需要一点帮助,因为我被困住了。我已经尝试了一切......我相信可以通过“add_action”来完成。帮助? :)

add_action('woocommerce_checkout_after_customer_details','inputs_after_cart');

function inputs_after_cart($checkout) {

    global $woocommerce;
    $items = $woocommerce->cart->get_cart();

    $i = 1;

    foreach($items as $item => $values) { 
        $_product = $values['data']->post;
        $quantity = $values['quantity'];
        $x = 1;

        while ($x <= $quantity) {

         echo '<div class="col-12 refresh-tickets"><h3>' . $_product->post_title .  __(' - Bilet ' . $x . ' ') .'</h3>';


         $namevar = 'name'.$x;
         $emailvar = 'email'.$x;


         woocommerce_form_field($namevar , array(

        'type' => 'text',
           'label'      => __('Name'),
           'placeholder'   => _x('', 'placeholder', 'woocommerce'),
           'required'   => true,
           'class'      => array(''),
           'clear'     => true,
               ));

        woocommerce_form_field($emailvar, array(

        'type' => 'text',
           'label'      => __('E-mail'),
           'placeholder'   => _x('', 'placeholder', 'woocommerce'),
           'required'   => false,
           'class'      => array(''),
           'clear'     => true,
               ));

                echo '</div>';
                $x++;
            }

            $i++;
            } 

}

【问题讨论】:

  • 当您将商品添加到购物车时,您特别想更新什么?
  • 如您所见,我试图根据购物车物品的数量添加woocommerce_form_field(姓名和电子邮件输入)。为每个项目添加一个字段。在更改项目数量时,应将输入数量更新为当前项目数。
  • 看这个例子,可以使用JS触发器“updated_cart_totals”stackoverflow.com/questions/39312360/…

标签: php wordpress templates woocommerce hook-woocommerce


【解决方案1】:

您可以编写脚本来侦听 WooCommerce javascript 触发事件,然后在触发时运行您自己的代码。这里是添加到购物车操作的 javascript 触发器。

$( document.body ).trigger( 'updated_cart_totals' );

使用此 javascript 挂钩该触发器。

$( document.body ).on( 'updated_cart_totals', function(event){
    //Run your own code here, use AJAX to call a PHP function to create new inputs
    $.ajax({
        url : 'http://yourwesbite.com/wp-admin/admin-ajax.php',
        type : 'post',
        data : {
            action : 'the_function_that_creates_inputs'
        },
        success : function( data ) {
            // data contains HTML inputs to display
        }
    });
});

【讨论】:

  • 但是如何使用 JS 触发呢? add_action('woocommerce_checkout_after_customer_details','inputs_after_cart');
  • 在第二个例子的JS代码中触发。您不使用 PHP 操作来拦截更改。客户端动作通过 JS 触发,服务器端动作使用 PHP 动作。您可以使用 JS 触发 AJAX 调用,该调用创建并返回您要显示的新输入。
猜你喜欢
  • 2016-10-09
  • 2017-01-20
  • 1970-01-01
  • 2017-01-11
  • 2018-02-17
  • 1970-01-01
  • 2023-04-08
  • 2017-04-24
  • 1970-01-01
相关资源
最近更新 更多