【问题标题】:How to post JSON array of objects using JQuery如何使用 JQuery 发布 JSON 对象数组
【发布时间】:2013-10-04 06:59:00
【问题描述】:

我在 Chrome 浏览器控制台中使用 Javascript/jQuery 将数据发布到页面。 (我在 Shopify 后台执行此操作,因为它无法批量导入运费)。

这是我正在使用的代码:

make_weight_based_shipping_rate(8267845, 98, 99, 'Test Shipping Rate', 59);

function make_weight_based_shipping_rate(cid, minWeight, maxWeight, name, price) {
  $.post('/admin/weight_based_shipping_rates.json', {
    weight_based_shipping_rate: {
      country_id: cid,
      name: name,
      offsets: [{disabled:true, offset:0, province_id:145570341}, {disabled:true, offset:0, province_id:145570345}], 
      weight_high: maxWeight,
      weight_low: minWeight,
      price: price
    }
  });
}

它运行良好,除了我的请求中包含一组对象的行 - 以“偏移量”开头的行。

如果我在这一行中只有一个 JSON 对象,而不是在数组中(通过排除方括号),则此代码有效。但是,作为一个数组,Shopify 返回错误“422(无法处理的实体)”,并且在响应正文中显示“{“errors”:{“shipping_rate_offsets”:[“无效”]}}。

我是否错误地格式化了这个 JSON 对象?如果没有,除了使用 JQuery Post 方法之外,还有其他方法可以实现吗?

【问题讨论】:

  • 您的 javascript(不是 JSON)看起来不错。不幸的是,这看起来像是 Shopify 处理该字段的方式的问题 - 大概该服务提供某种支持?你会在那里得到更准确的答案。
  • 谢谢 RGraham - 这是我看到其他人描述的解决方法。我不确定 Shopify 是否欣赏人们做这种事情——这不是他们官方 API 的一部分。
  • 我看到了你的帖子here。看起来这些人公开发布了该代码,所以我想说他们相当愿意支持它:)
  • 另外,我向他们的一位支持人员询问了有关 API 的问题,他们说在这里发布......!
  • 很好地使用了 Google :) 我希望他们会回答,但我认为 StackOverflow 的影响范围会更广。

标签: javascript jquery arrays json shopify


【解决方案1】:

我终于明白了。默认情况下,JQuery POST 和 AJAX 请求被编码为“application/x-www-form-urlencoded”。这在大多数情况下都有效,但是当它获取诸如 'offsets' 之类的数组时似乎会失败。

为了解决这个问题,首先我必须对提交的数据使用 JSON.stringify() 函数。然后在进行 POST 之前,我使用 ajaxSetup() 函数将内容类型设置为“application/json”。我现在修改的代码是:

make_weight_based_shipping_rate(8267845, 98, 99, 'Test Shipping Rate', 59);

function make_weight_based_shipping_rate(cid, minWeight, maxWeight, name, price) {
    $.ajaxSetup({
      contentType: "application/json; charset=utf-8"
    });
  $.post('/admin/weight_based_shipping_rates.json', JSON.stringify({
    weight_based_shipping_rate: {
      country_id: cid,
      name: name,
      offsets: [{disabled:true, offset:0, province_id:145570341}, {disabled:true, offset:0.00, province_id:145570345}], 
      weight_high: maxWeight,
      weight_low: minWeight,
      price: price
    }
  }));
}

我希望这对其他人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    • 2011-01-26
    • 2011-11-08
    • 2019-12-06
    • 2020-07-19
    • 1970-01-01
    相关资源
    最近更新 更多