首页 > 解决方案 > 使用带有 Shopify ajax api 的 jQuery 时出现“意外令牌:”错误

问题描述

错误

调用 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"]
}

代码

调用代码是:

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
        });
      }
    });

  });

平台

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

更多信息

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

有人知道这个错误吗?

我感谢每一个答案。

标签: javascriptajaxshopifyliquid

解决方案


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

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

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

jQuery.post如果这可行,您应该能够通过为数据类型 ( 'json')提供第四个参数来返回使用: https ://api.jquery.com/jquery.post/


推荐阅读