[英]Updating / refreshing custom mini-cart with ajax in Woocommerce
我正在尝试在Woocommerce中构建一个简单的界面,使用AJAX将产品直接添加到旁边的迷你购物车中,而不是每次将商品添加到购物车时都刷新页面。 不幸的是,我无法使AJAX正常工作,并且页面一直在刷新。
woocommerce.php- 默认的woocommerce页面 :
<?php
//LOOP THROUGH ALL PRODUCTS
$args = array( 'post_type' => 'product');
$loop = new WP_Query( $args );
echo "<ul class='mylisting'>";
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
$id = $product->get_id();
$item_name = $product->get_name();
if( $product->is_type( 'variable' ) ){
$class = "variable-product";
} else {
$class = NULL;
}
//OUTPUT PRODUCTS
?>
<li>
<a class="menu-link <?php echo $class; ?>" data-product_id="<?php echo $id; ?>" href="/wpdev/shop/?add-to-cart=<?php echo $id; ?>"><?php echo $item_name." - ".$id; ?></a>
</li>
<?php if( $product->is_type( 'variable' ) ) : ?>
<div id="product-popup-<?php echo $id; ?>" class="product-popup">
<div class="popup-inner">
<?php woocommerce_variable_add_to_cart(); ?>
</div>
</div>
<?php endif; ?>
<?php
endwhile;
echo "</ul>";
wp_reset_query();
?>
<!-- DISPLAY MINI CART -->
<div id="mini-cart-container">
<?php woocommerce_mini_cart(); ?>
</div>
main.js- 主javascript文件 :
$('.menu-link').click(function(){
jQuery.ajax({
url : woocommerce_params.ajax_url,
type : 'post',
data : {
'action': 'ajax_update_mini_cart'
},
success : function( response ) {
$('#mini-cart-container').html(response);
}
});
});
functions.php
function ajax_update_mini_cart() {
echo wc_get_template( 'cart/mini-cart.php' );
die();
}
add_filter( 'wp_ajax_nopriv_ajax_update_mini_cart', 'ajax_update_mini_cart' );
add_filter( 'wp_ajax_ajax_update_mini_cart', 'ajax_update_mini_cart' );
目的是获得woocommerce_mini_cart()
函数以用ajax更新。 这可能吗?
我怀疑问题出在我编写javascript ajax函数的方式上,但是我不确定。 任何帮助将不胜感激。
更新:现在已添加Moe的以下解决方案,该解决方案已停止了页面的重新加载,但购物车仍未更新。 在ajax_update_mini_cart()
函数中回显一些文本会在mini-cart-container
div中应放入mini-cart-container
文本内进行ajax,这证明(我认为)javascript函数和php函数正在工作。 我认为由于某些原因,当echo wc_get_template( 'cart/mini-cart.php' );
放在函数内部。 有人知道为什么是这样吗?
其以下href。 尝试以下
$('.menu-link').click(function(e){
e.preventDefault();
jQuery.ajax({
url : woocommerce_params.ajax_url,
type : 'post',
data : {
'action': 'ajax_update_mini_cart'
},
success : function( response ) {
$('#mini-cart-container').html(response);
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.