簡體   English   中英

購物車數據未使用ajax在shopify中更新

[英]cart data not update in shopify using ajax

我在 Shopify 中遇到問題。

我想使用 ajax 在按鈕點擊時更新購物車數量,但它會給出類似的錯誤

{"status":404,"message":"購物車錯誤","description":"找不到變體"}

這是我的ajax代碼,

 $('.adjust-plus').click(function(){
    var qty = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity').val();
    var varient = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity').attr('data-id');

    jQuery.ajax({
      type: 'POST',
      async: false,
      url: '/cart/update.js',
      data: { updates: { varient : qty } },
      dataType: 'json',
      success: function() { location.href = '/cart'; }
   });
 });

目前在這兩個變量值中都沒有任何值錯誤。

但是當 id 添加如下代碼時:

$('.adjust-plus').click(function(){
    var qty = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity').val();
    var varient = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity').attr('data-id');

    jQuery.ajax({
      type: 'POST',
      async: false,
      url: '/cart/update.js',
      data: { updates: { 15082896588867 : 2 } },
      dataType: 'json',
      success: function() { location.href = '/cart'; }
   });
 });

然后購物車更新成功。

首先,刪除async: false因為這是非常糟糕的做法,這里不需要,因為您正確使用了success回調。

問題本身是因為您不能使用變量作為您正在使用的語法的對象的鍵。 為了解決這個問題,您可以使用括號表示法,如下所示:

$('.adjust-plus').click(function() {
  var $quantity = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity');
  var qty = $quantity.val();
  var varient = $quantity.data('id');

  var data = { updates: {} };
  data.updates[varient] = qty;

  jQuery.ajax({
    type: 'POST',
    url: '/cart/update.js',
    data: data,
    dataType: 'json',
    success: function() { 
      location.href = '/cart'; 
    }
  });
});

暫無
暫無

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

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