簡體   English   中英

在 Shopify 商店中使用 AJAX 將所有產品變體和數量添加到購物車

[英]Add all product variant and quantity to the cart with AJAX in Shopify store

在我的 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 將所有產品變體添加到購物車並獲得:

必需參數缺失或無效:items

摘要:您提交的表單包含數量但不包含產品。 您還需要包含變體 ID。


在 for 循環中,您為產品中的所有變體創建了數量框,但缺少變體 ID。 當您將該數據發布到/cart/add.js ,Shopify 無法知道您嘗試將哪些產品放入購物車。

要一次在購物車中添加多個商品,我建議您查看 Shopify 的購物車 API 文檔: https ://shopify.dev/api/ajax/reference/cart#post-cart-add-js

要將多個項目添加到購物車,我們需要提交一個名為items的字段作為對象數組,指定要添加的 ID 以及可選的數量和我們附加的任何行項目屬性。

以下是對生成的代碼的外觀的快速思考:

<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 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>
   {% endfor %}
 </tr>

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

<script>
  let addToCartForm = document.querySelector('form[action="/cart/add"]');
  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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM