Shopify - 删除/更改多个购物车商品的数量

mat*_*gai 4 shopify

我想弄清楚如何调整多个购物车项目。

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

例如,将这两种产品添加到购物车:

Product 1
ID: 1000
Property: CustomProduct2

Product2 
ID: 1001
Property: CustomProduct2
Run Code Online (Sandbox Code Playgroud)

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

我知道下面的方法行不通,但假设如果可能的话,它会是这样的:

$(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,

       });
     });
Run Code Online (Sandbox Code Playgroud)

Dav*_*e B 5

这可以通过使用端点来实现/cart/update.js。(参见Shopify官方文档

文档忽略的一点是,您可以使用变体 ID或行项目的“键”值作为有效负载的键。这在使用行项目属性时非常重要,因为如果每次使用不同的行属性添加多次,则同一变体 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

   });
Run Code Online (Sandbox Code Playgroud)

创建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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

不管怎样,我们最终的 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) }
Run Code Online (Sandbox Code Playgroud)

});

希望这可以帮助!