Uncaught TypeError: Cannot read property 'id' of undefined in shopify custom cart popup jQuery ajax

Uncaught TypeError: Cannot read property 'id' of undefined in shopify custom cart popup jQuery ajax

我的 jQuery AJAX 代码出错。 Uncaught TypeError: Cannot read property 'id' of undefined。我不明白我该如何解决这个问题。当我尝试通过单击变体添加产品时,显示此错误。这是我的 shopify development 网站。下面是我的 jQuery 代码。

$('.varients-item').on('click', function(){
    var obj = $(this);
    var variants_id = $(this).attr("data-variant");
    $.ajax({
        type: 'POST',
        url: '/cart/add.js',
        data: {
            quantity: 1,
            id: variants_id
        },
        dataType: 'json',
        success: function (data) {
            $.ajax({
                type: 'GET',
                dataType: 'jsonp',
                url: '/cart.json',
                success: function(cart){

                    var item_count = cart['item_count'];
                    var total_price = cart['total_price']/100;

                    //If there are items in cart
                    if ( item_count > 0 ) {
                        // cart count
                        $('.cart-item-count span').text(item_count);

                        // mini cart data
                        $('.cart-popup').attr('id','cartPopup');
                        $('.cartpopup-total .price').text( '£' + total_price.toFixed(2) );


                        var cart_list = [];

                        for( var i = 0; i < item_count; i++ ){
                            if ( cart['items'][i]['id'] != null ) {
                                var item_id = cart['items'][i]['id'];
                                var product_title = cart['items'][i]['product_title'];
                                // var product_title = data['items'][i]['title'];
                                var product_handle = cart['items'][i]['handle'];
                                var quantity = cart['items'][i]['quantity'];
                                var line_price = cart['items'][i]['price']/100;
                                var url = cart['items'][i]['url'];
                                var image_url = cart['items'][i]['image'];
                                var variants = cart['items'][i]['variant_options'];

                                if ( product_title == 'Gift Wrap' ) {
                                    var product_url = product_title;
                                } else {
                                    var product_url = '<a href="' + url + '">' + product_title + '</a>';
                                }

                                var options = [];
                                for ( var o = 0; o < variants.length; o++ ) {
                                    var selected = cart['items'][i]['variant_options'][o];
                                    if ( selected !== 'Default Title' ) {
                                        options.push( selected + '<br>' );
                                    }
                                };
                                var selected_options = options.join('');

                                cart_list.push(
                                    '<div class="cartpopup-item d-flex flex-row">'+
                                        '<div class="cartpopup-item-image">'+
                                            '<a href="' + url + '">'+
                                                '<img class="img-fluid d-block" src="' + image_url + '"  alt="' + product_title + '" />'+
                                            '</a>'+
                                        '</div>'+
                                        '<div class="cartpopup-item-content d-flex flex-column">'+
                                            '<h5>' + product_url + '</h5>'+
                                            '<span class="variant">' + selected_options + '</span>'+
                                            '<span class="price">£' + total_price.toFixed(2) + '</span>'+
                                            '<div class="quantity-box d-flex flex-row">'+
                                                '<button class="quantity-button qminus" role="button" type="button" data-variant="' + item_id + '"><i class="fal fa-minus"></i></button>'+
                                                '<input class="quantity-input" type="number" disabled name="updates[]" id="updates_' + item_id + '" value="' + quantity + '" min="1" />'+
                                                '<button class="quantity-button qplus" role="button" type="button" data-variant="' + item_id + '"><i class="fal fa-plus"></i></button>'+
                                            '</div>'+
                                            '<div class="d-flex flex-row">'+
                                                '<a class="remove" data-cart-remove-id="' + item_id + '" href="/cart/change?line=' + item_count + '&amp;quantity=0">Remove</a>'+
                                            '</div>'+
                                        '</div>'+
                                    '</div>'
                                );
                            } //endif
                        }; // endfor

                        $('.cartpopup-body').html( cart_list.join('') );
                    }
                    $('.cart-popup').addClass('active');
                    $('body').addClass('cartpopup-active');
                    $('body').append(
                        '<div class="popupbackdrop"></div>'
                    );
                }
            });
        }
    });
});

当尝试在点击变体按钮时添加相同的变体两次时会显示此错误。当从购物车中删除所有产品并刷新页面然后再次添加产品时,它将完美运行。

I'm struggling about this issue in many days but no success.

如评论中所述,这是您尝试访问不可用数据时的常见问题。在这种情况下,这背后的原因是您对 Shopify 购物车中的 item_count 变量的误解。如果您查看 Shopify AJAX API 参考,item_count 是您购物车中的商品总数。例如,您可能 item_count 为 3,而 items 数组中只有 1 个对象,数量为 3。但是,您的代码不处理这种情况,并始终假设对象的数量将始终等于 item_count。此外,要遍历数组,不要依赖 item_count 而是 items 数组长度。这样做,您的代码将像

$('.varients-item').on('click', function(){
    var obj = $(this);
    var variants_id = $(this).attr("data-variant");
    $.ajax({
        type: 'POST',
        url: '/cart/add.js',
        data: {
            quantity: 1,
            id: variants_id
        },
        dataType: 'json',
        success: function (data) {
            $.ajax({
                type: 'GET',
                dataType: 'jsonp',
                url: '/cart.json',
                success: function(cart){
                    // change the below line
                    var item_count = cart['items'].length;
                    var total_price = cart['total_price']/100;

                    //If there are items in cart
                    if ( item_count > 0 ) {
                        // cart count
                        $('.cart-item-count span').text(item_count);

                        // mini cart data
                        $('.cart-popup').attr('id','cartPopup');
                        $('.cartpopup-total .price').text( '£' + total_price.toFixed(2) );


                        var cart_list = [];

                        for( var i = 0; i < item_count; i++ ){
                            if ( cart['items'][i]['id'] != null ) {
                                var item_id = cart['items'][i]['id'];
                                var product_title = cart['items'][i]['product_title'];
                                // var product_title = data['items'][i]['title'];
                                var product_handle = cart['items'][i]['handle'];
                                var quantity = cart['items'][i]['quantity'];
                                var line_price = cart['items'][i]['price']/100;
                                var url = cart['items'][i]['url'];
                                var image_url = cart['items'][i]['image'];
                                var variants = cart['items'][i]['variant_options'];

                                if ( product_title == 'Gift Wrap' ) {
                                    var product_url = product_title;
                                } else {
                                    var product_url = '<a href="' + url + '">' + product_title + '</a>';
                                }

                                var options = [];
                                for ( var o = 0; o < variants.length; o++ ) {
                                    var selected = cart['items'][i]['variant_options'][o];
                                    if ( selected !== 'Default Title' ) {
                                        options.push( selected + '<br>' );
                                    }
                                };
                                var selected_options = options.join('');

                                cart_list.push(
                                    '<div class="cartpopup-item d-flex flex-row">'+
                                        '<div class="cartpopup-item-image">'+
                                            '<a href="' + url + '">'+
                                                '<img class="img-fluid d-block" src="' + image_url + '"  alt="' + product_title + '" />'+
                                            '</a>'+
                                        '</div>'+
                                        '<div class="cartpopup-item-content d-flex flex-column">'+
                                            '<h5>' + product_url + '</h5>'+
                                            '<span class="variant">' + selected_options + '</span>'+
                                            '<span class="price">£' + total_price.toFixed(2) + '</span>'+
                                            '<div class="quantity-box d-flex flex-row">'+
                                                '<button class="quantity-button qminus" role="button" type="button" data-variant="' + item_id + '"><i class="fal fa-minus"></i></button>'+
                                                '<input class="quantity-input" type="number" disabled name="updates[]" id="updates_' + item_id + '" value="' + quantity + '" min="1" />'+
                                                '<button class="quantity-button qplus" role="button" type="button" data-variant="' + item_id + '"><i class="fal fa-plus"></i></button>'+
                                            '</div>'+
                                            '<div class="d-flex flex-row">'+
                                                '<a class="remove" data-cart-remove-id="' + item_id + '" href="/cart/change?line=' + item_count + '&amp;quantity=0">Remove</a>'+
                                            '</div>'+
                                        '</div>'+
                                    '</div>'
                                );
                            } //endif
                        }; // endfor

                        $('.cartpopup-body').html( cart_list.join('') );
                    }
                    $('.cart-popup').addClass('active');
                    $('body').addClass('cartpopup-active');
                    $('body').append(
                        '<div class="popupbackdrop"></div>'
                    );
                }
            });
        }
    });
});