我正在尝试在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中对文本进行ajax,这证明(我认为)javascript函数和php函数正在工作。我认为由于某种原因,将echo wc_get_template( 'cart/mini-cart.php' );
放在函数内部时会出现问题。有人知道为什么吗?
答案 0 :(得分:0)
其跟随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);
}
});
});