Shopify 2.0 如何将多个产品添加到购物车?

问题描述 投票:0回答:1

我目前正在使用 Shopify 的 Sense 主题,与此相关,我需要重写他们的“添加到购物车”功能,以便它可以一次将多个产品添加到购物车。

我有一个设置,其中一些附加产品已添加到产品页面,客户可以将其添加到所谓的捆绑包中。当客户点击主产品上的“添加到购物车”时,不仅应该将主产品添加到购物车中,还应该将捆绑包中选定的产品添加到购物车中。每个捆绑产品都有一个关联的表单,就像主产品一样。

这是 Shopify 的“添加到购物车”脚本:

onSubmitHandler(evt) {
  evt.preventDefault();
  if (this.submitButton.getAttribute('aria-disabled') === 'true') return;

  this.handleErrorMessage();

  this.submitButton.setAttribute('aria-disabled', true);
  this.submitButton.classList.add('loading');
  this.querySelector('.loading-overlay__spinner').classList.remove('hidden');

  const config = fetchConfig('javascript');
  config.headers['X-Requested-With'] = 'XMLHttpRequest';
  delete config.headers['Content-Type'];

  const formData = new FormData(this.form);
  if (this.cart) {
    formData.append('sections', this.cart.getSectionsToRender().map((section) => section.id));
    formData.append('sections_url', window.location.pathname);
    this.cart.setActiveElement(document.activeElement);
  }
  config.body = formData;
  console.log("Form data: " + formData);

  fetch(`${routes.cart_add_url}`, config)
    .then((response) => response.json())
    .then((response) => {
      if (response.status) {
        this.handleErrorMessage(response.description);

        const soldOutMessage = this.submitButton.querySelector('.sold-out-message');
        if (!soldOutMessage) return;
        this.submitButton.setAttribute('aria-disabled', true);
        this.submitButton.querySelector('span').classList.add('hidden');
        soldOutMessage.classList.remove('hidden');
        this.error = true;
        return;
      } else if (!this.cart) {
        window.location = window.routes.cart_url;
        return;
      }

      this.error = false;
      const quickAddModal = this.closest('quick-add-modal');
      if (quickAddModal) {
        document.body.addEventListener('modalClosed', () => {
          setTimeout(() => { this.cart.renderContents(response) });
        }, { once: true });
        quickAddModal.hide(true);
      } else {
        this.cart.renderContents(response);
      }
    })
    .catch((e) => {
      console.error(e);
    })
    .finally(() => {
      this.submitButton.classList.remove('loading');
      if (this.cart && this.cart.classList.contains('is-empty')) this.cart.classList.remove('is-empty');
      if (!this.error) this.submitButton.removeAttribute('aria-disabled');
      this.querySelector('.loading-overlay__spinner').classList.add('hidden');
    });
}

我想象在每个选定的捆绑产品上创建一个 forEach 循环,并为每个产品创建一个新的 formData,然后将它们与主产品的 formData 合并在一起。然而,我还没能让它完全发挥作用。

您可以在此处阅读有关该主题的 Shopify 购物车 API 文档:

https://shopify.dev/docs/api/ajax/reference/cart

请随时提供一个可能的解决方案,或者让我知道完成它会花费多少,特别是如果有人可以在今天星期一之前解决它。 :)

javascript html css shopify shopify-api
1个回答
0
投票

你可以喜欢这个 vs api /cart/add.js enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.