You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress集成Yotpo Rewards至WooCommerce:优惠券表单提交异常

解决WooCommerce结账页Yotpo优惠券提交重渲染问题

你遇到的核心问题是直接调用form.submit()会触发浏览器默认的表单提交,导致整页刷新,而WooCommerce的结账优惠券功能是通过AJAX异步处理的,必须触发它内置的事件逻辑。

以下是修正后的脚本:

document.body.addEventListener("yotpoLoyaltyDiscountApplied", function(e) {
    const discountCodeInput = document.getElementById('coupon_code');
    if (!discountCodeInput) return;

    // 设置优惠券代码并触发change事件,让WooCommerce感知到值更新
    discountCodeInput.value = e.detail.discountCode;
    discountCodeInput.dispatchEvent(new Event('change', { bubbles: true }));

    // 找到优惠券表单的提交按钮,模拟点击(WooCommerce通过按钮点击绑定AJAX逻辑)
    const submitBtn = document.querySelector('.checkout_coupon button[type="submit"]');
    if (submitBtn) {
        submitBtn.click();
    }
});

关键修正点:

  • 触发change事件:WooCommerce的表单监听依赖输入框的change事件来识别值变化,直接赋值不会触发这个事件,必须手动派发。
  • 模拟按钮点击而非直接提交表单:WooCommerce给优惠券提交按钮绑定了AJAX处理逻辑,点击按钮会触发异步请求更新订单金额,不会导致整页刷新。
  • 提前return避免无效操作:如果找不到输入框直接退出,减少冗余代码。

另外,需要确保你的脚本在DOM完全加载后执行,避免找不到元素的情况:

document.addEventListener('DOMContentLoaded', function() {
    document.body.addEventListener("yotpoLoyaltyDiscountApplied", function(e) {
        const discountCodeInput = document.getElementById('coupon_code');
        if (!discountCodeInput) return;

        discountCodeInput.value = e.detail.discountCode;
        discountCodeInput.dispatchEvent(new Event('change', { bubbles: true }));

        const submitBtn = document.querySelector('.checkout_coupon button[type="submit"]');
        if (submitBtn) {
            submitBtn.click();
        }
    });
});

内容的提问来源于stack exchange,提问作者Jake Mulhern

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 01:01:00