繁体   English   中英

如何使用JQuery发布对象的JSON数组

[英]How to post JSON array of objects using JQuery

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

效果很好,除了我的请求中包含对象数组的一行-以“ offsets”开头的行。

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

我是否正确格式化了此JSON对象? 如果不是,是否还有其他方法可以实现此目的,而不是使用JQuery Post方法?

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

为了解决这个问题,首先我必须对提交的数据使用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
    }
  }));
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM