问题:
我正在尝试在调用AJAX时显示JavaScript警报。但是,当我刷新页面时,警报才会成功激活。
这是触发javascript IF购物车商品>的功能的开始。 2:
因此,如果Woocommerce购物车中有超过2个项目,请运行Javascript警报...
add_action( 'wp_footer', 'trigger_popup' );
function trigger_popup() {
global $woocommerce;
$maximum_num_products = 2;
$cart_num_products = WC()->cart->get_cart_contents_count();
if( $cart_num_products > $maximum_num_products ) {
然后我试图在调用ajax时显示javascript警告:
我研究过Global Ajax Event Handlers,我认为 $ .ajaxComplete 是什么需要,但它并没有触发javascript。我还尝试设置URL Ajax JS Handler以尝试触发警报...
?>
<script src="https://unpkg.com/sweetalert2@7.20.1/dist/sweetalert2.all.js"></script>
<script type="text/javascript">
//EXECUTE FOR AJAX?
$( document ).ajaxComplete(function(){
//URL NEEDED FOR AJAX TO WORK?
url: '/?wc-ajax=add_to_cart',
// ALERT CODE HERE
swal(
'You added all the items!',
'Proceed to checkout?',
'success')
//END OF ALERT CODE
})(jQuery);
</script>
<?php
}
}
作为FYI,这是Javascript的工作版本触发警报ON PAGE REFRESH,但不适用于AJAX:
如果购物车中有超过2件商品,我会刷新页面。这成功触发了javascript警报。
?>
<script src="https://unpkg.com/sweetalert2@7.20.1/dist/sweetalert2.all.js"></script>
<script type="text/javascript">
swal(
'You added all the items!',
'Proceed to checkout?',
'success')
</script>
<?php
}
}
如何在Ajax上触发Javascript警报或在每次调用Ajax时检查是否满足IF条件?
谢谢!
答案 0 :(得分:2)
尝试以下代码,其中jQuery代码将在&#34; added_to_cart&#34;上发送ajax请求。委托活动。在该请求上,php将获得购物车项目计数并将其返回给jQuery。如果该计数满足某些条件,它将显示您的甜蜜警报消息:
// Wordpress Ajax: Get different cart items count
add_action( 'wp_ajax_nopriv_checking_cart_items', 'checking_cart_items' );
add_action( 'wp_ajax_checking_cart_items', 'checking_cart_items' );
function checking_cart_items() {
if( isset($_POST['added']) ){
// For 2 different cart items
echo json_encode( sizeof( WC()->cart->get_cart() ) );
}
die(); // To avoid server error 500
}
// The Jquery script
add_action( 'wp_footer', 'custom_popup_script' );
function custom_popup_script() {
?>
<script src="https://unpkg.com/sweetalert2@8.8.1/dist/sweetalert2.all.min.js"></script>
<script src="https://unpkg.com/promise-polyfill@8.1.0/dist/polyfill.min.js"></script>
<script type="text/javascript">
jQuery( function($){
// The Ajax function
$(document.body).on('added_to_cart', function() {
console.log('event');
$.ajax({
type: 'POST',
url: wc_add_to_cart_params.ajax_url,
data: {
'action': 'checking_cart_items',
'added' : 'yes'
},
success: function (response) {
if( response >= 2 ){
swal(
'You added all the items!',
'Proceed to checkout?',
'success'
);
}
}
});
});
});
</script>
<?php
}
代码放在活动子主题(或活动主题)的function.php文件中。经过测试和工作。
答案 1 :(得分:0)
我想补充一点,当前有一个插件可以为购物车提供rest api。
https://wordpress.org/plugins/cart-rest-api-for-woocommerce/
使用该插件,您可以侦听添加项目并获取项目计数
print "pattern exists\n" if exists $reads{'.ISPV3-21*02'};