jQuery 在 Shopify 中使用 AJAX 添加到购物车

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20643484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:14:46  来源:igfitidea点击:

Add to Cart using AJAX in Shopify

jqueryajaxshopify

提问by damon

By default, when you add a product to a cart in Shopify, it will redirect you to the Cart page. What I want to do is have it add to the cart without refreshing the page at all.

默认情况下,当您在 Shopify 中将产品添加到购物车时,它会将您重定向到购物车页面。我想要做的是将它添加到购物车而不刷新页面。

Shopify provides some instructions on how to do this here: http://docs.shopify.com/support/your-website/themes/can-i-use-ajax-api, but I am pretty unfamiliar with AJAX, so it's giving me a bit of trouble.

Shopify 在此处提供了一些有关如何执行此操作的说明:http://docs.shopify.com/support/your-website/themes/can-i-use-ajax-api ,但我对 AJAX 非常不熟悉,因此它提供了我有点麻烦。

They provide a JavaScript file (http://cdn.shopify.com/s/shopify/api.jquery.js?a1c9e2b858c25e58ac6885c29833a7872fcea2ba) with some functions, the principle ones being:

他们提供了一个带有一些功能的 JavaScript 文件(http://cdn.shopify.com/s/shopify/api.jquery.js?a1c9e2b858c25e58ac6885c29833a7872fcea2ba),主要功能是:

// -------------------------------------------------------------------------------------
// POST to cart/add.js returns the JSON of the line item associated with the added item.
// -------------------------------------------------------------------------------------
Shopify.addItem = function(variant_id, quantity, callback) {
  var quantity = quantity || 1;
  var params = {
    type: 'POST',
    url: '/cart/add.js',
    data: 'quantity=' + quantity + '&id=' + variant_id,
    dataType: 'json',
    success: function(line_item) { 
      if ((typeof callback) === 'function') {
        callback(line_item);
      }
      else {
        Shopify.onItemAdded(line_item);
      }
    },
    error: function(XMLHttpRequest, textStatus) {
      Shopify.onError(XMLHttpRequest, textStatus);
    }
  };
  jQuery.ajax(params);
};

and

// ---------------------------------------------------------
// POST to cart/add.js returns the JSON of the line item.
// ---------------------------------------------------------
Shopify.addItemFromForm = function(form_id, callback) {
    var params = {
      type: 'POST',
      url: '/cart/add.js',
      data: jQuery('#' + form_id).serialize(),
      dataType: 'json',
      success: function(line_item) { 
        if ((typeof callback) === 'function') {
          callback(line_item);
        }
        else {
          Shopify.onItemAdded(line_item);
        }
      },
      error: function(XMLHttpRequest, textStatus) {
        Shopify.onError(XMLHttpRequest, textStatus);
      }
    };
    jQuery.ajax(params);
};

I'm really not positive which one is better to use for what I'm trying to do, so I've tried both. First, I tried to arrange my product submit form like this:

我真的不确定哪一个更适合我正在尝试做的事情,所以我都试过了。首先,我尝试像这样安排我的产品提交表单:

<form action="/cart/add" method="post" class="clearfix product_form" data-money-format="{{ shop.money_format }}" data-option-index="{{ option_index }}" id="product-form-{{ product.id }}">
    // yadda yadda
    <input type="submit" name="add" value="Add to Cart" id="add-to-cart" class="action_button" onclick="return false; Shopify.addItem({{variant.id}}, 1, 'okay')"/>
</form>

Where I just added the onclick="return false; Shopify.addItem({{variant.id}}, 1, 'okay')"to the input (return falseto prevent redirect and the Shopify.addItemfunction to add the item via Ajax.) Neither of those things actually work.

在我刚刚添加onclick="return false; Shopify.addItem({{variant.id}}, 1, 'okay')"到输入的地方(return false以防止重定向和Shopify.addItem通过 Ajax 添加项目的功能。)这些东西实际上都不起作用。

I've also tried:

我也试过:

<form action="/cart/add" method="post" class="clearfix product_form" data-money-format="{{ shop.money_format }}" data-option-index="{{ option_index }}" id="product-form-{{ product.id }}">
    // yadda yadda
    <input type="submit" name="add" value="Add to Cart" id="add-to-cart" class="action_button" onclick="Shopify.addItemFromForm({{variant.id}}, 'okay')"/>
</form>

This also seems to have no effect.

这似乎也没有效果。

They provide a demo page for their Ajax here: http://mayert-douglas4935.myshopify.com/pages/api

他们在这里为他们的 Ajax 提供了一个演示页面:http: //mayert-douglas4935.myshopify.com/pages/api

And when I try and copy the code for their Shopify.addItemFromForm example, it gives me this error alert when I try and add to cart: "Cart Error(400): We were not able to add this item to your shopping cart because no variant ID was passed to us. (request_id: 864f24c82d1bfbae4542a9603674861e)"

当我尝试复制他们 Shopify.addItemFromForm 示例的代码时,当我尝试添加到购物车时,它给了我这个错误警报:“购物车错误(400):我们无法将此商品添加到您的购物车,因为没有变体 ID 已传递给我们。(request_id: 864f24c82d1bfbae4542a9603674861e)"

What am I doing wrong? Am I using the wrong functions? Am I passing the wrong arguments? I've been trying different variants of the above for 2 days now, and I haven't made any noticeable progress. Any help is greatly appreciated.

我究竟做错了什么?我是否使用了错误的功能?我是否传递了错误的论点?我已经尝试了上述的不同变体 2 天了,但我没有取得任何明显的进展。任何帮助是极大的赞赏。



UpdateResolved it with some tinkering and Steph's answer. The code that worked:

更新通过一些修补和斯蒂芬的回答解决了它。有效的代码:

{% if product.options.size > 1 %}
       <a onclick="Shopify.addItem($('#product-select-{{ product.id }} option:selected').val(), 1); return false" href="#">Add Item</a>
      {% elsif product.options.size == 1 and (product.variants.size > 1 or product.options[0] != "Title") %}
       <a onclick="Shopify.addItem($('#product-select-{{ product.id }} option:selected').val(), 1); return false" href="#">Add Item</a>
      {% else %}
       <a onclick="Shopify.addItem({{ product.variants.first.id }}, 1); return false" href="#">Add Item</a>
      {% endif %}

First two conditions check if product has options, if so, get variant value from the selected option. The else is for items with no options, and {{ product.variants.first.id }}gets the correct variant id.

前两个条件检查产品是否有选项,如果有,从所选选项中获取变体值。else 用于没有选项的项目,并{{ product.variants.first.id }}获取正确的变体 ID。

回答by Steph Sharp

I think you want to be using Shopify.addItemand not Shopify.addItemFromForm(unless of course you have your variant id and quantity in a form that you want to use).

我认为你想使用Shopify.addItem而不是Shopify.addItemFromForm(当然,除非你有你想要使用的形式的变体 ID 和数量)。

Here's an example of both ways. I modified the code from the demo pageyou linked to in your question.

这是两种方式的示例。我修改了您在问题中链接到的演示页面中的代码。

Shopify.addItem:

Shopify.addItem:

<a onclick=" Shopify.addItem(jQuery('#product-select option:selected').val(), 1); return false" href="#">Shopify.addItem</a>

Shopify.addItemFromForm:

Shopify.addItemFromForm:

<form id="add-item-form" method="post" action="#">
    variant: <input class="update" type="text" value="324748289" name="id" size="8">
    qty: <input type="text" value="1" name="quantity" size="3">
</form>
<p>
    <a onclick=" Shopify.addItemFromForm('add-item-form'); return false" href="#">Shopify.addItemFromForm</a>('add-item-form')
</p>

A couple of things to check in your code:

需要检查代码的几件事:

  • Is {{variant.id}}returning the correct value for the currently selected variant?
  • The Shopify.addItemFromFormfunction takes a form id as a parameter, not a variant id.
  • 是否{{variant.id}}为当前选择的变体返回正确的值?
  • Shopify.addItemFromForm函数采用表单 id 作为参数,而不是变体 id。