LoginSignup
125
115

More than 5 years have passed since last update.

$.ajax でオブジェクトの配列を POST したい

Last updated at Posted at 2014-12-16

事案

$.ajax({ type: 'POST'}) でオブジェクトの配列を Rails に送るぞー!

POST するコード

ajax.js.coffee
$.ajax
  type: 'POST'
  url: url
  dataType: 'json'
  data:
    users: [
      room: 201
      name: 'ゆの'
    ,
      room: 202
      name: '宮子'
    ]

理想

params
{
  "users" => [{
    "room" => 201,
    "name" => "ゆの"
  }, {
    "room" => 202,
    "name" => "宮子"
  }]
}

現実

FormData
users[0][room]:201
users[0][name]:ゆの
users[1][room]:202
users[1][name]:宮子
params
"users" => {
  "0" => {
    "room" => "201",
    "name" => "ゆの"
   },
  "1" => {
    "room" => "202",
    "name" => "宮子"
  }
}

▂▅▇█▓▒░('ω')░▒▓█▇▅▂うわあああああああ

原因

jQuery API Documentation を見ると、

It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

と書いてありました。Object や Array を渡した場合は jQuery が $.param でシリアライズするんですね。

解決策

  • $.ajax のオプションで contentType: 'application/json' を指定する。
  • data の値を JSON.stringify などで JSON 文字列に変換する。
ajax.js.coffee
$.ajax
  type: 'POST'
  url: url
  dataType: 'json'
  contentType: 'application/json'
  data: JSON.stringify(
    users: [
      room: 201
      name: 'ゆの'
    ,
      room: 202
      name: '宮子'
    ]
  )
RequestPayload
{"users":[{"room":201,"name":"ゆの"},{"room":202,"name":"宮子"}]}
params
{
  "users" => [{
    "room" => 201,
    "name" => "ゆの"
  }, {
    "room" => 202,
    "name" => "宮子"
  }]
}

✌ ('ω' ✌ )三 ✌ ('ω') ✌ 三( ✌ 'ω') ✌ 送れた!

参考

125
115
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
125
115