“意外令牌:”在 Shopify ajax api 中使用 jQuery 时出错

Dan*_*eno -3 javascript ajax liquid shopify

错误

调用 shopify ajax api 时,我在开发人员工具控制台中收到错误消息。

Uncaught SyntaxError: Unexpected token :

在 javascript 控制台中单击此错误会奇怪地显示有效 JSON 的响应:

{
"id":19728251846714,
"properties":null,
"quantity":1,
"variant_id":19728251846714,
"key":"19728251846714:f1a55a69aed71e7c10ca53fd3549edda",
"title":"Ritual Petalos de rosas y vino tinto - Obispado",
"price":139900,
"original_price":139900,
"discounted_price":139900,
"line_price":139900,
"original_line_price":139900,
"total_discount":0,
"discounts":[],
"sku":"",
"grams":0,
"vendor":"Casa Azul Spa",
"taxable":false,
"product_id":1959512244282,
"gift_card":false,
"url":"\/products\/ritual-petalos-de-rosas-y-vino-tinto?variant=19728251846714",
"image":"https:\/\/cdn.shopify.com\/s\/files\/1\/0087\/2267\/7818\/products\/PETALOS_DE_ROSAS_Y_VINO_TINTO.jpg?v=1538589224",
"handle":"ritual-petalos-de-rosas-y-vino-tinto",
"requires_shipping":false,
"product_type":"",
"product_title":"Ritual Petalos de rosas y vino tinto",
"product_description":"\u0026lt;!--\ntd {border: 1px solid #ccc;}br {mso-data-placement:same-cell;}\n--\u003eRitual Pétalos de Rosas y Vino tinto, Exquisito masaje que ofrece bienestar, relajación e hidrata la piel. Realizamos el ritual con mascarilla hidratante y antioxidante, piedras calientes, y cuarzos para ofrecer un delicioso y aromático descanso a todo el cuerpo.",
"variant_title":"Obispado",
"variant_options":["Obispado"]
}
Run Code Online (Sandbox Code Playgroud)

代码

调用代码为:

jQuery.getJSON('/products/'+getProduct.product_handle+'.js', function(product) {

    product.variants.forEach(function(variant) {
      if (getProduct.sucursal == variant.title){
        jQuery.post('/cart/add.js', {
          quantity: 1,
          id: variant.id
        });
      }
    });

  });
Run Code Online (Sandbox Code Playgroud)

平台

我正在使用模板语言 Liquid 使用 Shopify,在这个 Liquid 中,我有一个<script>运行 AJAX的标签,用于从 Shopify 调用方法。

更多信息

我知道错误必须有 javascript 语法,但就像我之前说的那样,我没有看到错误。

有人知道这个错误吗?

我感谢每一个答案。

Dav*_*e B 5

尝试使用jquery.ajax调用的长格式手动指定所有 AJAX 参数:

jQuery.ajax({
  url:'/cart/add.js',
  type: 'post',
  dataType: 'json',
  data: { quantity:1, variant: variant.id }
  // Optional: success/error functions
})
Run Code Online (Sandbox Code Playgroud)

建立在其他答案的基础上,可能是 jQuery 期待一种类型的响应标头,但实际上接收的是另一种类型。

如果这有效,您应该可以jQuery.post通过为数据类型 ( 'json')提供第四个参数来重新使用:https : //api.jquery.com/jquery.post/