事案
$.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" => "宮子"
}]
}
✌ ('ω' ✌ )三 ✌ ('ω') ✌ 三( ✌ 'ω') ✌ 送れた!