Ajax(Asynchronous JavaScript and XML)是一种用于创建快速动态网页的技术,它允许在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页内容。在WooCommerce中,使用Ajax可以从迷你购物车中删除优惠券。
以下是一个简单的示例,展示如何使用Ajax从WooCommerce迷你购物车中删除优惠券:
<button id="remove-coupon" data-coupon="SUMMER20">删除优惠券</button>
$(document).ready(function() {
$('#remove-coupon').click(function() {
var couponCode = $(this).data('coupon');
$.ajax({
url: wc_add_to_cart_params.ajax_url, // WooCommerce提供的Ajax URL
type: 'POST',
data: {
action: 'woocommerce_remove_coupon', // 自定义的Ajax动作
coupon_code: couponCode
},
success: function(response) {
// 更新迷你购物车显示
$('#mini-cart').html(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('Error: ' + textStatus + ' - ' + errorThrown);
}
});
});
});
add_action('wp_ajax_woocommerce_remove_coupon', 'remove_coupon_from_cart');
add_action('wp_ajax_nopriv_woocommerce_remove_coupon', 'remove_coupon_from_cart');
function remove_coupon_from_cart() {
if (isset($_POST['coupon_code'])) {
$coupon_code = sanitize_text_field($_POST['coupon_code']);
WC()->cart->remove_coupon($coupon_code);
ob_start();
wc_get_template('cart/mini-cart.php'); // 加载迷你购物车的模板
$response = ob_get_clean();
echo $response;
}
wp_die();
}
sanitize_text_field
等函数对输入数据进行清理,并确保只有授权用户才能执行敏感操作。通过以上步骤,你可以有效地使用Ajax来增强WooCommerce迷你购物车的功能,提升用户体验。
领取专属 10元无门槛券
手把手带您无忧上云