Woocommerce aJax将优惠券代码应用于购物篮 [英] Woocommerce aJax apply coupon code to basket
问题描述
我试图在按下按钮时将优惠券代码应用于购物篮.我有以下代码:-
I am attempting to apply a coupon code to the basket on a button press. I have the following code:-
coupon = jQuery(this).data('coupon');
data = {coupon_code : coupon};
jQuery.post( "?wc-ajax=apply-coupon", { coupon_code: coupon }).done(function( data ) {
alert( "Data Loaded: " + data );
});
我可以看到以下数据正在解析到服务器:-
I can see the following data is being parsed to the server:-
coupon_code: 10percentdiscount
10percentdiscount
存在.
我发送请求后,服务器未发回响应.
The Server is not sending back a response once I have sent the request.
我是正确发出此请求还是其他方法?
Am I correctly making this request or is there another way?
谢谢.
推荐答案
我会这样做:
在header.php或页面中定义ajax网址,您是否要添加优惠券
Define ajax url in header.php or in page would you add coupon
<script type="text/javascript" language="javascript">
var ajax_url = "<?php bloginfo('url'); ?>/wp-admin/admin-ajax.php";
</script>
在function.php中,您必须定义ajax调用
In function.php you must define ajax call
function implement_ajax() {
include(TEMPLATEPATH . '/ajax_return.php');
}
add_action('wp_ajax_my_special_action', 'implement_ajax');
add_action('wp_ajax_nopriv_my_special_action', 'implement_ajax');
在ajax_return.php中,您输入了将优惠券添加到woocommerce的代码:
In ajax_return.php you past code that add coupon to woocommerce:
if (isset($_POST['couponcode']))
{ apply_coupon($_POST['couponcode']); };
function apply_coupon($couponcode) {
global $woocommerce; WC()->cart->remove_coupons();
$ret = WC()->cart->add_discount( $couponcode );
$array = array('return' => $ret); print_r($array);
}
exit;
您的jQuery.post会变成这样:
Your jQuery.post will became this:
<script type="text/javascript">
jQuery(function(){
coupon = jQuery(this).data('coupon');
jQuery.post(ajax_url, {action : 'my_special_action', couponcode : coupon}, return_function, 'JSON');
});
function return_function(data)
{
console.log(data.return); //contains true if coupon was applied
}
</script>
如果需要,请调用return_function来管理响应.
If you need, call return_function to manage response.
这篇关于Woocommerce aJax将优惠券代码应用于购物篮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!