javascript - 在 Shopify 中使用 ajax 更新购物车数量时避免使用产品类型

标签 javascript jquery ajax

我正在使用一个脚本,该脚本使用 Ajax 更新我的 Shopify 商店中的购物车计数。这工作正常,但是我有一个特定的产品类型,我不想将其包含在计数中。我已经设法使用下面的代码(从论坛帖子中找到)使其在正常页面刷新上工作,但无法理解如何编辑 Ajax 脚本,以便使用 Ajax 更新计数,但避免产品类型 mw_product_option。

有人可以帮我解决这个问题吗?提前致谢,我将不胜感激。

<a href="/cart" id="cartCount">
{% assign num = 0 %}     
{% for item in cart.items %}            
{% if item.product.type != "mw_product_option" %}       
     {% capture temp %}{{ num | plus: item.quantity }}{% endcapture %} 
{% endif %}
{% assign num = temp %}
{% endfor %}
<span class="CartCount-alt">{{ num }}</span>

我想更新 Ajax 脚本以避免计算“mw_product_option”:

// Update cart count and show cart link.
   $.getJSON(_config.shopifyAjaxCartURL, function(cart) {
   if (_config.cartCountSelector && $(_config.cartCountSelector).size()) {
     var value = $(_config.cartCountSelector).html() || '0';
     $(_config.cartCountSelector).html(value.replace(/[0-9]+/,cart.item_count)).removeClass('hidden-count');
   }

完整的 Ajax 脚本:

Shopify.AjaxifyCart = (function($) {

  // Some configuration options.
  // I have separated what you will never need to change from what
  // you might change.

  var _config = {

// What you might want to change
addToCartBtnLabel:             'Add to cart',
addedToCartBtnLabel:           'Added to cart!',
addingToCartBtnLabel:          'Adding...',
soldOutBtnLabel:               'Sold Out',
howLongTillBtnReturnsToNormal: 1000, // in milliseconds.
cartCountSelector:             '.cart-count, #cart-count a:first, #gocart p a, #cart .checkout em, .item-count, .CartCount, .CartCount-alt',
cartTotalSelector:             '#cart-price',
// 'aboveForm' for top of add to cart form, 
// 'belowForm' for below the add to cart form, and 
// 'nextButton' for next to add to cart button.
feedbackPosition:              'belowForm',

// What you will never need to change
addToCartBtnSelector:          '[type="submit"]',
addToCartFormSelector:         'form[action="/cart/add"]',
shopifyAjaxAddURL:             '/cart/add.js',
shopifyAjaxCartURL:            '/cart.js'
  };

  // We need some feedback when adding an item to the cart.
  // Here it is.  
  var _showFeedback = function(success, html, $addToCartForm) {
$('.ajaxified-cart-feedback').remove();
var feedback = '<p class="ajaxified-cart-feedback ' + success + '">' + html + '</p>';
switch (_config.feedbackPosition) {
  case 'aboveForm':
    $addToCartForm.before(feedback);
    break;
  case 'belowForm':
    $addToCartForm.after(feedback);
    break;
  case 'nextButton':
  default:
    $addToCartForm.find(_config.addToCartBtnSelector).after(feedback);
    break;   
}
// If you use animate.css
// $('.ajaxified-cart-feedback').addClass('animated bounceInDown');
$('.ajaxified-cart-feedback').slideDown();
  };
  var _setText = function($button, label) {
    if ($button.children().length) {
  $button.children().each(function() {
    if ($.trim($(this).text()) !== '') {
      $(this).text(label);
    }
  });
}
else {
  $button.val(label).text(label);
}
  };
  var _init = function() {   
    $(document).ready(function() { 
      $(_config.addToCartFormSelector).submit(function(e) {
        e.preventDefault();
        var $addToCartForm = $(this);
    var $addToCartBtn = $addToCartForm.find(_config.addToCartBtnSelector);
    _setText($addToCartBtn, _config.addingToCartBtnLabel);
    $addToCartBtn.addClass('disabled').prop('disabled', true);
    // Add to cart.
    $.ajax({
      url: _config.shopifyAjaxAddURL,
      dataType: 'json',
      type: 'post',
      data: $addToCartForm.serialize(),
      success: function(itemData) {
        // Re-enable add to cart button.
        $addToCartBtn.addClass('inverted');
        _setText($addToCartBtn, _config.addedToCartBtnLabel);
        _showFeedback('success','<div class="added-to-cart"><i class="fa fa-check large-icon"></i><i class="fa fa-check"></i> Added to your cart! <a href="/cart">View cart</a> or <a href="/collections/all">continue shopping</a>.</div>',$addToCartForm);
        window.setTimeout(function(){
          $addToCartBtn.prop('disabled', false).removeClass('disabled').removeClass('inverted');
          _setText($addToCartBtn,_config.addToCartBtnLabel);
        }, _config.howLongTillBtnReturnsToNormal);
        // Update cart count and show cart link.
        $.getJSON(_config.shopifyAjaxCartURL, function(cart) {
          if (_config.cartCountSelector && $(_config.cartCountSelector).size()) {
            var value = $(_config.cartCountSelector).html() || '0';
            $(_config.cartCountSelector).html(value.replace(/[0-9]+/,cart.item_count)).removeClass('hidden-count');
          }
          if (_config.cartTotalSelector && $(_config.cartTotalSelector).size()) {
            if (typeof Currency !== 'undefined' && typeof Currency.moneyFormats !== 'undefined') {
              var newCurrency = '';
              if ($('[name="currencies"]').size()) {
                newCurrency = $('[name="currencies"]').val();
              }
              else if ($('#currencies span.selected').size()) {
                newCurrency = $('#currencies span.selected').attr('data-currency');
              }
              if (newCurrency) {
                $(_config.cartTotalSelector).html('<span class=money>' + Shopify.formatMoney(Currency.convert(cart.total_price, "{{ shop.currency }}", newCurrency), Currency.money_format[newCurrency]) + '</span>');
              } 
              else {
                $(_config.cartTotalSelector).html(Shopify.formatMoney(cart.total_price, "{{ shop.money_format | remove: "'" | remove: '"' }}"));
              }
            }
            else {
              $(_config.cartTotalSelector).html(Shopify.formatMoney(cart.total_price, "{{ shop.money_format | remove: "'" | remove: '"' }}"));
            }
          };
        });        
      }, 
      error: function(XMLHttpRequest) {
        var response = eval('(' + XMLHttpRequest.responseText + ')');
        response = response.description;
        if (response.slice(0,4) === 'All ') {
          _showFeedback('error', response.replace('All 1 ', 'All '), $addToCartForm);
          $addToCartBtn.prop('disabled', false);
          _setText($addToCartBtn, _config.soldOutBtnLabel);
          $addToCartBtn.prop('disabled',true);
        }
        else {
          _showFeedback('error', '<i class="fa fa-warning"></i> ' + response, $addToCartForm);
          $addToCartBtn.prop('disabled', false).removeClass('disabled');
          _setText($addToCartBtn, _config.addToCartBtnLabel);
        }
      }
    });   
    return false;    
  });
});
  };
   return {
    init: function(params) {
    // Configuration
    params = params || {};
    // Merging with defaults.
    $.extend(_config, params);
    // Action
    $(function() {
      _init();
    });
},    
getConfig: function() {
  return _config;
}
  }  
})(jQuery);

Shopify.AjaxifyCart.init();

最佳答案

好的,正如我所看到的,您需要的一切是将服务器脚本转换为 js 格式。它将是这样的:

$.getJSON(_config.shopifyAjaxCartURL, function(cart) {
    if (_config.cartCountSelector && $(_config.cartCountSelector).size()) {
        var value = $(_config.cartCountSelector).html() || '0',
            itemsCount = 0;
        $.each(cart.items, function(key, item) {
            if (item.product_type != "mw_product_option") {       
                 itemsCount += item.quantity;
            }
        });
        $(_config.cartCountSelector).html(value.replace(/[0-9]+/, itemsCount)).removeClass('hidden-count');
    }        
    ...
});

关于javascript - 在 Shopify 中使用 ajax 更新购物车数量时避免使用产品类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38955321/

相关文章:

javascript - Nodejs Express客户端在访问main之前无法GET/xxx.html

javascript - NightwatchJs 在控制台、属性和值中打印元素文本时出现问题

javascript - 在以编程方式添加到 DOM 的 <a> 元素上捕获点击事件

c# - 从 onchange 触发 .click() 时,IE9 上出现 "SCRIPT5 Access is denied"错误

ajax - Knockout JS - 使用 AJAX 调用更新 viewModel

jquery - 将非框架代码实现到框架中,例如 laravel 或 codeigniter

javascript - 如何使用jquery中的选择框将页面内容加载到div?

javascript - 构造函数和普通函数的区别

javascript - 如何编写一个程序来确保两个字段中输入的密码匹配?

javascript - jquery 对象 key 对未定义