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

如何在WooCommerce单品页启用嵌入结账表单的Ajax提交功能?

问题:WooCommerce单品页面嵌入结账表单后无法使用Ajax提交

我通过以下代码在WooCommerce单品页面的短描述区域嵌入结账表单短代码:

add_filter('woocommerce_short_description','ts_add_text_short_descr');
function ts_add_text_short_descr($description){
  $text="[woocommerce_checkout]";
  return $description.$text;
}

表单可以正常显示,但点击「下单」按钮时,无法通过Ajax提交表单,而是直接跳转到结账页面。请问如何启用该表单的Ajax提交功能?


解决方案

WooCommerce的[woocommerce_checkout]短代码默认仅在结账页面加载Ajax提交所需的脚本与事件绑定,直接嵌入单品页面时会缺失这些资源,需要手动补充以下步骤:

1. 强制加载结账相关脚本

在主题的functions.php文件中添加代码,确保单品页面加载结账功能所需的核心脚本:

add_action('wp_enqueue_scripts', 'ts_enqueue_checkout_scripts_on_single_product');
function ts_enqueue_checkout_scripts_on_single_product() {
    if (is_product()) {
        wp_enqueue_script('wc-checkout');
        wp_enqueue_script('wc-ajax');
    }
}

2. 重新绑定Ajax提交事件

由于表单是动态插入的,页面初始加载时的事件绑定不会生效,需要添加自定义JS重新绑定提交事件:

add_action('wp_footer', 'ts_rebind_checkout_ajax_events');
function ts_rebind_checkout_ajax_events() {
    if (!is_product()) return;
    ?>
    <script>
        jQuery(document).ready(function($) {
            $('body').on('submit', 'form.checkout', function(e) {
                const $form = $(this);
                if ($form.hasClass('processing')) return;
                
                e.preventDefault();
                $form.addClass('processing');
                
                $.ajax({
                    type: 'POST',
                    url: wc_checkout_params.checkout_url,
                    data: $form.serialize(),
                    dataType: 'json',
                    success: function(res) {
                        $form.removeClass('processing');
                        
                        if (res.result === 'success') {
                            window.location.href = res.redirect;
                        } else {
                            $('.woocommerce-error').remove();
                            if (res.messages) $form.prepend(res.messages);
                        }
                    },
                    error: () => {
                        $form.removeClass('processing');
                        $form.prepend('<div class="woocommerce-error">提交失败,请稍后重试</div>');
                    }
                });
            });
        });
    </script>
    <?php
}

3. 补充说明

  • 上述代码已经包含基础的表单提交状态管理与错误处理,可根据实际需求调整提示文案或验证逻辑。
  • 测试前请清空浏览器缓存,确保新加载的脚本生效。
  • 若主题自定义了结账表单结构,需确保选择器form.checkout能正确匹配到目标表单。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:57:26