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

Shopify产品页加入购物车按钮代码修改:点击后跳转结账页

实现Shopify产品页加购后直接跳转结账的代码修改方案

方法一:直接修改表单提交目标(最简单)

Shopify支持直接将产品表单提交到结账页面,无需先加入购物车再跳转。找到你的产品页面模板文件(通常是sections/main-product.liquid或snippets/product-form.liquid,不同主题路径可能有差异),找到产品加购表单代码,修改action属性:

原表单代码示例:

<form action="/cart/add" method="post" class="product-form">
  <input type="hidden" name="id" value="{{ product.selected_or_first_available_variant.id }}">
  <input type="number" name="quantity" value="1" min="1">
  <button type="submit" class="add-to-cart">加入购物车</button>
</form>

修改后:

<form action="/checkout" method="post" class="product-form">
  <input type="hidden" name="id" value="{{ product.selected_or_first_available_variant.id }}">
  <input type="number" name="quantity" value="1" min="1">
  <button type="submit" class="add-to-cart">加入购物车并结账</button>
</form>

提交这个表单时,系统会自动将商品加入购物车并直接跳转到结账页面,无需额外逻辑。

方法二:AJAX加购后跳转(支持自定义提示)

如果需要先完成加购操作、显示成功提示后再跳转,可通过JavaScript监听表单提交事件:

在产品模板文件的末尾(或主题的自定义JS文件中)添加以下代码:

// 监听产品表单提交
document.querySelector('.product-form').addEventListener('submit', function(e) {
  e.preventDefault(); // 阻止默认提交行为
  const formData = new FormData(this);

  // 用AJAX完成加购
  fetch('/cart/add.js', {
    method: 'POST',
    body: formData
  })
  .then(response => {
    if (!response.ok) throw new Error('加购失败');
    return response.json();
  })
  .then(() => {
    // 可添加自定义提示,比如:
    // alert('商品已加入购物车,正在跳转至结账页面');
    window.location.href = '/checkout'; // 跳转结账
  })
  .catch(err => {
    console.error(err);
    // 显示错误提示给用户
    alert('加购失败,请重试');
  });
});

注意事项

  • 不同主题的模板结构可能不同,需确认产品表单的类名或选择器是否正确(比如有的主题用product-form__form而非product-form)
  • 若产品有多变体,确保{{ product.selected_or_first_available_variant.id }}能正确获取选中的变体ID
  • 测试前建议备份主题代码,避免修改出错导致页面异常

内容的提问来源于stack exchange,提问作者Thái Học Nguyễn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 15:22:07