在Shopify商店使用AJAX将所有产品变体和数量添加到购物车中 [英] Add all product variant and quantity to the cart with AJAX in Shopify store

查看:41
本文介绍了在Shopify商店使用AJAX将所有产品变体和数量添加到购物车中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Shopify商店的产品页面上,我有一个表,其中包含不同的标题、价格和输入数量列。我是否可以使用AJAX将产品每个变体的所有输入数量添加到购物车中?

我的表:

<form action="/cart/add" method="post" >

 <tr>
   {% for variant in product.variants %}
 {% assign variant = product.selected_or_first_available_variant %}
     <td>{{ variant.title }}</td>
     <td>{{ variant.price | money }}</td>
     <td>  
       <input name="quantity" inputmode="numeric" value="0">
     </td>
   {% endfor %}
 </tr>

<input type="submit" value="Add to cart">
</form>



<script>
let addToCartForm = document.querySelector('form[action="/cart/add"]');
let formData = new FormData(addToCartForm);
 fetch('/cart/add.js', {
   method: 'POST',
   body: formData
 })
 .then(response => {
   return response.json();
 })
 .catch((error) => {
   console.error('Error:', error);
});
</script>
和一些Shopify文档 https://shopify.dev/api/ajax/reference/cart#post-cart-add-js

我正在尝试使用AJAX和GET将所有产品变体添加到购物车中进行一次调用:

必需参数缺失或无效:项目

推荐答案

摘要:您的表单深渊翻滚包含数量,但没有产品。您还需要包括变量ID。


在for循环中,您已经为产品中的所有变体创建了数量框,但缺少变量ID。当您将数据发布到/cart/add.js时,Shopify无法知道您尝试将哪些产品放入购物车。

要在购物车中一次添加多个商品,我建议您查看购物车API的Shopify文档:https://shopify.dev/api/ajax/reference/cart#post-cart-add-js

要将多个项目添加到购物车,我们需要将名为items的字段作为对象数组提交,以指定要添加的ID及其数量(可选)以及我们要附加的任何行项目属性。

以下是关于结果代码可能的外观的快速想法:

<form class="custom-product-form" action="/cart/add" method="post">
  <table>
   {% for variant in product.variants %}
   <tr>
     <td>{{ variant.title }}</td>
     <td>{{ variant.price | money }}</td>
     <td class="item-submission">
       <!-- Added hidden input for the variant ID -->
       <input type="hidden" name="id" value="{{ variant.id }}"/>
       <input name="quantity" inputmode="numeric" value="0">
     </td>
   </tr>
   {% endfor %}
  </table>
  <input type="submit" value="Add to cart">
</form>

<script>
  let addToCartForm = document.querySelector('.custom-product-form');
  addToCartForm.addEventListener('submit', (evt) => {
    evt.preventDefault();
    // Update to create an object based on the multiple input rows
    let items = [];
    let rows = evt.currentTarget.querySelectorAll('.item-submission');

    for(let i=0; i<rows.length; i++) {
      // Get the variant ID and quantity for each row. 
      let itemData = rows[i];
      let id = parseInt(itemData.querySelector('[name="id"]').value );
      let qty = parseInt(itemData.querySelector('[name="quantity"]').value );
      // We don't care about any rows with a quantity of 0
      if(id && qty > 0){
        items.push({ id: id, quantity: qty });
      }
    }
    if(!items.length){
      // Do something to tell the customer that there's nothing to add if all quantities were 0
      return;
    }

    return fetch('/cart/add.js', {
       method: 'POST',
       body: JSON.stringify({ items: items }),
       headers: { 'Content-type': 'application/json' },
       credentials: 'include' 
       // Note: Including credentials sends the cart cookie, which is important to make sure that the items go into the shopper's cart and not into a void
     })
     .then(response => {
       return response.json();
     })
     .catch((error) => {
       console.error('Error:', error);
    });
  })
</script>

这篇关于在Shopify商店使用AJAX将所有产品变体和数量添加到购物车中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆