duanhuan8983 2017-01-11 14:27
浏览 59
已采纳

Woocommerce aJax将优惠券代码应用于购物篮

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

The 10percentdiscount exists.

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?

Thank you in advance.

  • 写回答

2条回答 默认 最新

  • dongtang6681 2017-01-11 14:44
    关注

    I would do so:

    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>
    

    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');
    

    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;
    

    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>
    

    If you need, call return_function to manage response.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题