在Shopify中使用ajax更新购物车计数时,请避免使用产品类型

时间:2016-08-15 12:43:20

标签: 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();

1 个答案:

答案 0 :(得分:1)

好的,因为我可以看到你需要的所有内容都是将服务器脚本转换为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');
    }        
    ...
});