可以通过在自定义主题functions.php文件中添加以下代码来解决此问题:
add_action('wp_ajax_nopriv_remove_cart_item', 'remove_cart_item_callback');
add_action('wp_ajax_remove_cart_item', 'remove_cart_item_callback');
function remove_cart_item_callback() {
$cart_item_key = $_POST['cart_item_key'];
$woocommerce = WC();
$woocommerce->cart->set_quantity($cart_item_key, 0);
wp_send_json_success();
wp_die();
}
然后,在您的Ajax请求中,您需要将过程的PHP文件指向您自己的处理程序,如下所示:
jQuery(document).on('click', '.remove-cart-item', function(e){
e.preventDefault();
var cart_item_key = jQuery(this).attr('data-cart-item-key');
var data = {
'action': 'remove_cart_item',
'cart_item_key': cart_item_key
};
jQuery.post(your_ajax_url_goes_here, data, function(response){
// Remove the item from the DOM.
// Your code here.
});
});
最后,您也需要在functions.php中保存以下代码片段,使您的Ajax请求有效。这将为您的WordPress站点添加一个全局Javascript变量,该变量是您的Ajax处理程序目录的引用。
add_action('wp_enqueue_scripts', 'enqueue_scripts_and_styles');
function enqueue_scripts_and_styles() {
wp_localize_script('jquery', 'my_ajax_object',
array('ajax_url' => admin_url('admin-ajax.php'))
);
}
请记得将上述代码中的“your_ajax_url_goes_here”替换为您的自定义代码的PHP文件的URL。
上一篇:Ajax在执行控制器方法之前失败
下一篇:ajax怎么连接sql数据库