简体   繁体   中英

How to post JSON array of objects using JQuery

I am using Javascript/jQuery in the Chrome browser console to post data to a page. (I'm doing this in Shopify admin, because it doesn't have the capability to bulk import shipping rates).

This is the code I am using:

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

It works well, except for one line of my request which has an array of objects - the line that begins with 'offsets'.

If I only have one JSON object on this line, and not in an array (by excluding the square brackets), this code works. However, as an array, Shopify comes back with the error '422 (Unprocessable Entity)' and in the body of the response it says '{"errors":{"shipping_rate_offsets":["is invalid"]}}'.

Am I formatting this JSON object incorrectly? If not, is there some other way I can achieve this rather than use the JQuery Post method?

I eventually figured it out. By default, JQuery POST and AJAX requests are encoded as "application/x-www-form-urlencoded". This works most of the time, but it seems to fail when it gets an array such as 'offsets'.

To get around this, first I had to use the JSON.stringify() function on the data being submitted. Then prior to making the POST, I used the ajaxSetup() function to set the content-type to "application/json". My modified code is now:

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

I hope this helps others.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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