简体   繁体   English

Shopify 购物车 AJAX 请求返回不一致

[英]Shopify Cart AJAX Request Returning Inconsistently

I am attempting to post 2 items to a shopping cart, in one click.我正在尝试一键将 2 件商品发布到购物车。 I've built a form with hidden checkboxes that carry the relevant product attributes I need to do that.我已经建立了一个带有隐藏复选框的表单,这些复选框带有我需要这样做的相关产品属性。 I have a loop going over the form's child checkboxes to pull that info and invoke the function for the post request.我有一个循环遍历表单的子复选框以提取该信息并为发布请求调用该函数。

The problem is that sometimes it does add both items (yay!) but sometimes it'll load only the first item and sometimes only the second item.问题是有时它确实添加了两个项目(耶!)但有时它只会加载第一个项目,有时只加载第二个项目。 There's no error code in the console for me to go off of so I'm wondering what I'm missing.控制台中没有错误代码可供我关闭,所以我想知道我错过了什么。

EDIT: 19 hours in. I'm thinking the issue is coming from the function that opens the cart that is firing when the first item is returned.编辑:19 小时后。我认为问题出在打开购物车的功能,该购物车在返回第一个项目时触发。 Both of the calls are being return successfully but that code is interrupting it being added to the cart.两个调用都成功返回,但该代码正在中断它被添加到购物车。

EDIT 2: This post describes the issue I'm having.编辑2: 这篇文章描述了我遇到的问题。 I need to make one request and then move on to the next one.我需要提出一个请求,然后继续下一个请求。 I think I'm going to have to build an array with the items from the form.我想我将不得不用表单中的项目构建一个数组。

My JS我的JS

const freeAddOnForm = document.getElementById('free-addon-form'),
      freeAddOnButton = freeAddOnForm[2];

function getDataForm(e) {
    e.preventDefault();

    loadingBarTrigger('start');

    for(let i = 0; i < 2; i++) {
        itemAdd(
            freeAddOnForm[i].getAttribute('data-quickadd-id'), 
            freeAddOnForm[i].getAttribute('data-quickadd-properties'), 
            (freeAddOnForm[i].getAttribute('data-quickadd-quantity'))
                ? freeAddOnForm[i].getAttribute('data-quickadd-quantity')
                : 1, 
            (!html.is('#cart')) ? true : false,
            (html.is('#cart')) ? true : false
        )
    }   
}

document.addEventListener('DOMContentLoaded', function (){
    freeAddOnButton.addEventListener('click', getDataForm, false);
})

The itemAdd function that makes the post request to the cart:向购物车发出 post 请求的 itemAdd 函数:

const itemAdd = (variantId, properties, qty, openCart, reloadPage) => {
    $.ajax({
        type: 'POST',
        dataType: 'html',
        url: `/cart/add.js`,
        data: 
            {
                id: variantId,
                quantity: qty,
                properties: (properties) 
                    ? JSON.parse(properties) : null
            },
        error: function(data) {
            console.error(data);

            loadingBarTrigger('done');
        },
        success: function() {
            loadingBarTrigger('move');

            $.ajax({
                url: '/cart',
                dataType: 'html',
                error: function(data) {
                console.error(data);

                loadingBarTrigger('done');
            },
                success: function(data) {
                    let minicartContent = $('#minicart-content');
                    let cartItemsHtml = $(data).find('#cart-content #cart-items').html();

                    // insert or prepend cart HTML
                    (minicartContent.find('#cart-items').length)
                        ? minicartContent.find('#cart-items').html(cartItemsHtml)
                        : minicartContent.prepend(cartItemsHtml);

                    // remove giftbox content if exists
                    (minicartContent.find('#cart-giftbox .item-info').length)
                        ? minicartContent.find('#cart-giftbox .item-info').remove()
                        : '';

                    loadingBarTrigger('done');
                    cartTotalUpdate();

                    // open cart
                    (openCart && !html.is('#cart'))
                        ? minicartTrigger.trigger('click') : '';

                    (reloadPage)
                        ? location.reload() : '';
                }
            });
        }
    });
}

Ended up putting both items as objects into an array and sending them to the Shopify AJAX api together.最后将这两个项目作为对象放入一个数组中,并将它们一起发送到 Shopify AJAX api。 Seems to work, a couple little bugs to hammer out with the slide out cart at the end of the function.似乎可行,在功能结束时用滑出推车敲出几个小错误。

const itemsAddAjax = (itemsQueue, openCart, reloadPage) => {
        console.log(itemsQueue)

        $.post(`/cart/add.js`, {
            items: [
                {
                quantity: itemsQueue[0].qty,
                id: itemsQueue[0].id,
                properties: (itemsQueue[0].properties) 
                    ? JSON.parse(itemsQueue[0].properties) : null
                },
                {
                quantity: itemsQueue[1].qty,
                id: itemsQueue[1].id,
                properties: (itemsQueue[1].properties) 
                    ? JSON.parse(itemsQueue[1].properties) : null
                }
            ],
            
            error: function(items) {
                // console.error(items);

                loadingBarTrigger('done');
            },
            success: function() {
                loadingBarTrigger('move');
              

                $.ajax({
                    url: '/cart',
                    dataType: 'html',
                    error: function(items) {
                        console.error(items[0]);
                        loadingBarTrigger('done');
                    },
                    success: function(items) {

I think the easy and Simple way is to use the following code and add number of items in "items" array with their respective data.我认为简单的方法是使用以下代码并在“项目”数组中添加项目数量及其各自的数据。

let formData = {
 'items': [{
  'id': 36110175633573,
  'quantity': 2
  },
{
  'id': 36110175623388,
  'quantity': 1
  }
]
};

fetch(window.Shopify.routes.root + 'cart/add.js', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(formData)
})
.then(response => {
  return response.json();
})
.catch((error) => {
  console.error('Error:', error);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM