首页 > 解决方案 > Issue with ajax function

问题描述

I've been working on a function that popultes a drawer cart using ajax, so the page doesn't have to be refreshed to see the new items in the cart. This is the relevant ajax call:

        $.ajax({
          url: _config.shopifyAjaxAddURL,
          dataType: 'json',
          type: 'post',
          data: $addToCartForm.serialize(),
          success: function(itemData) {
            $.getJSON(_config.shopifyAjaxCartURL, function(cart) {
              $('.drawer-refresh-hide').css('display','block');
               $.each(cart.items, function(index, cartItem) {
                 var line= index +1;
                 var cents = "";

if (cartItem.price % 100 < 10) {
 cents = "0";
}
var price = parseInt(cartItem.price/100) + "." + cents + cartItem.price % 100;
        $('.dropdown-cart').append("<tr class='responsive-table-row'><td class='cart-first'><a href='"+ cartItem.url +"'</a><img src='"+ cartItem.image +"'/><a href='/cart/change?line="+ line +"&amp;quantity=0' class='qty-remove small--hide'><p class='small'>{{ 'cart.general.remove' | t }}</p></a><input type='submit' name='update' value='{{ 'cart.general.update' | t }}' class='qty-remove small small--hide ajax-submit'></td><td class='cart-second'><span class='CartTitle'>"+ cartItem.product_title +"</span>{% unless item.product.has_only_default_variant %}<p>"+ cartItem.variant_title+"</p>{% endunless %}{% if "+ cartItem.available +" %}<span class='stock-message'>In Stock</span>{% endif %}</td><td class='cart-mobile-last'><span>Quantity</span></td><td data-label='test' class='mobile-edit-container'><div class='cart-quantity'><input type='button' value='+' class='qtyplus qty-plus-2' field='updates_"+ cartItem.id +"'></input><input type='number' name='updates[]' id='updates_"+ cartItem.id +"' class='quantity' value='"+ cartItem.quantity +"'/><input type='button' value='-' class='qtyminus qtyminus-2' field='updates_"+ cartItem.id +"'></input></div></td><td data-label='{{ 'cart.label.total' | t }}' class='small--hide'>£"+ price +"</td></tr>");
             });
     $(function(index, cartItem) {
             var line2= index +1;
             var cents2 = "";

if (cart.total_price % 100 < 10) {
cents2 = "0";
}
var price2 = parseInt(cart.total_price/100) + "." + cents2 + cart.total_price % 100;
               $('.dropdown-cart-2').append("<div class='cart-total'><span class='order-first'>Total</span><span class='order-second'>"+ price2 +"</span></div>");
});
            });
            $('.drawer-main-form').css('display','none');
            // Re-enable add to cart button.
            $addToCartBtn.addClass('inverted');
            _setText($addToCartBtn, _config.addedToCartBtnLabel);
            _showFeedback('success',' ',$addToCartForm);
            window.setTimeout(function(){
              $addToCartBtn.prop('disabled', false).removeClass('disabled').removeClass('inverted');
              $addToCartForm.find('.swatch-element.option-selected').removeClass("option-selected");
              _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 ') {
              $addToCartBtn.prop('disabled', false);
              _setText($addToCartBtn, _config.soldOutBtnLabel);
              $addToCartBtn.prop('disabled',true);
            }
            else {
              $addToCartBtn.prop('disabled', false).removeClass('disabled');
              _setText($addToCartBtn, _config.addToCartBtnLabel);
            }
          }
        });

This works, but I'm having an issue with the for each function of the cart items, so this bit:

              $.each(cart.items, function(index, cartItem) {
                 var line= index +1;
                 var cents = "";

if (cartItem.price % 100 < 10) {
 cents = "0";
}
var price = parseInt(cartItem.price/100) + "." + cents + cartItem.price % 100;
        $('.dropdown-cart').append("<tr class='responsive-table-row'><td class='cart-first'><a href='"+ cartItem.url +"'</a><img src='"+ cartItem.image +"'/><a href='/cart/change?line="+ line +"&amp;quantity=0' class='qty-remove small--hide'><p class='small'>{{ 'cart.general.remove' | t }}</p></a><input type='submit' name='update' value='{{ 'cart.general.update' | t }}' class='qty-remove small small--hide ajax-submit'></td><td class='cart-second'><span class='CartTitle'>"+ cartItem.product_title +"</span>{% unless item.product.has_only_default_variant %}<p>"+ cartItem.variant_title+"</p>{% endunless %}{% if "+ cartItem.available +" %}<span class='stock-message'>In Stock</span>{% endif %}</td><td class='cart-mobile-last'><span>Quantity</span></td><td data-label='test' class='mobile-edit-container'><div class='cart-quantity'><input type='button' value='+' class='qtyplus qty-plus-2' field='updates_"+ cartItem.id +"'></input><input type='number' name='updates[]' id='updates_"+ cartItem.id +"' class='quantity' value='"+ cartItem.quantity +"'/><input type='button' value='-' class='qtyminus qtyminus-2' field='updates_"+ cartItem.id +"'></input></div></td><td data-label='{{ 'cart.label.total' | t }}' class='small--hide'>£"+ price +"</td></tr>");
             });

It populates the cart alright, but the items show multiple times if multiple products are added. So an example scenario: The user adds Product A. Product A then shows in the drawer cart. Without refreshing the page the user then adds Product B. The cart drawer now shows: -Product A -Product B -Product A (again)

So the each is executed twice (which makes sense) but not sure how I can fix this so products which have been added already don't dublicate?

标签: javascriptajax

解决方案


删除函数$('.dropdown-cart')之前的行each

$('.dropdown-cart tr').remove();
$.each(cart.items ...)

推荐阅读