Shopify - remove/change 多个购物车商品的数量

Shopify - remove/change quantity of multiple cart items

我想知道如何调整多个购物车项目。

本质上,我们有一个自定义订单页面,可以将多个产品添加到购物车。添加的所有产品都具有相同的唯一性 属性。

例如将这两款产品加入购物车:

Product 1
ID: 1000
Property: CustomProduct2

Product2 
ID: 1001
Property: CustomProduct2

最终用户只将其视为一种产品,因此我想要一种方法来通过一个按钮删除或调整具有匹配属性的所有产品的数量。

我知道下面的方法行不通,但我想如果可能的话,应该是这样的:

$(document).on('click','.remove',function(e){
  var property = $(this).attr('data-property');
       $.ajax({
         type: 'POST',
         url: '/cart/add.js',
         data: {
           quantity: 0,
           id: *,
           properties: {
             'Property': data-property
           }
         },
         dataType: 'json',
         async:false,

       });
     });

这可以通过使用 /cart/update.js 端点来实现。 (参见 Shopify's official documentation

文档遗漏的一点是,您可以使用变体 ID 或行项目的 'key' 值 作为有效负载的键。这在使用订单项属性时很重要,因为如果多次使用不同的订单项属性多次添加相同的变体 ID,则可能会出现在多行中。但是,保证购物车中每一行的密钥都是唯一的。

因此,示例请求为:

$.ajax({
     type: 'POST',
     url: '/cart/update.js',
     data: {
       updates:{
          "100000:abcdef":0, // Use the line-item key inside the quotes 
          "100001:xyzwnm":0
       }
     },
     dataType: 'json',
     async:false,  // Be warned, async:false has been deprecated in jQuery for a long time and is not recommended for use. It's generally recommended to use callbacks or promises instead

   });

创建 updates 数据的一种方法是通过简单的 for 循环。假设您将购物车的当前内容保存到名为 cart 的变量中,它可能如下所示:

var updateData = {}
for(var i=0; i < cart.items.length; i++){
  var item = cart.items[i];
  if( /* Check for item that needs to be removed */){
    updateData[item.key] = 0;
  }
}
// Now you can make your AJAX call using this updateData object

如果你想花哨的话,你也可以使用 array.reduce 来做到这一点:

var updateData = cart.items.reduce(function(acc, item){
  if( /* Check for item that we want to remove */){
    acc[item.key] = 0
  }
  return acc;
}, {})
// Now make your AJAX call using the updateData that we created

无论如何,我们最终的 AJAX 调用现在看起来像这样:

$.ajax({
 type: 'POST',
 url: '/cart/update.js',
 data: {
   updates: updateData
 },
 dataType: 'json',
 success: function(cart){ console.log('Hooray!', cart) },
 error: function(err){ console.error('Booo!', err) }

});

希望对您有所帮助!

使用 fetch 删除

正在从购物车中删除一件商品。

function removeItemFromCart (item) {
  fetch('/cart/update.js', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      updates: {
        [item.key]: 0
      }
    })
  }).then(response => response.json())
    .then((newCart) => {
      console.log('Updated cart:', newCart)
    })
    .catch(console.error)
}