HTML 表单:POST 一个对象数组 [英] HTML Form: POST an array of objects
问题描述
提交班级名册.一次添加3个学生.每个学生都有第一个、最后一个年龄.
Submitting a class roster. Adding 3 students at once. Each student has first, last, age.
问题:我们怎样才能让所有的学生都出现在一个数组中?
Question: How can we get all of the students in an array of arrays?
students[0] => Array (
["first"] => "first name for 0",
["last"] => "last name for 0",
["age"] => "age for 0"
),
students[1] => Array (
["first"] => "first name for 1",
["last"] => "last name for 1",
["age"] => "age for 1"
),
...
详情
对于一名学生:
Details
For one student:
<input type="text" name="first">
<input type="text" name="last">
<input type="text" name="age">
我们可以像这样在单独的数组中返回多个学生:
We can return multiple students in separate arrays like this:
<input type="text" name="students[first][]">
<input type="text" name="students[last][]">
<input type="text" name="students[age][]">
返回一个包含 firsts、lasts 和年龄的数组
which returns an array of firsts, lasts and ages
students["first"] = [array of first names]
students["last"] = [array of last names]
students["age"] = [array of ages]
理论上,我们可以通过访问相同的索引(例如每个数组的3")来获取学生的所有信息.
Theoretically we can get all the info for a student by accessing the same index (say "3" for each array).
我们不想以编程方式在表单中添加索引.
不想:
We do not want to programatically add an index in the form.
Do not want:
<input type="text" name="students[hardcoded_index][first]">
<input type="text" name="students[hardcoded_index][last]">
<input type="text" name="students[hardcoded_index][age]">
如果出于任何原因,我们对视图使用 Rails,但可以使用表单助手或 HTML.
If for any reason it matters, we are using Rails for views but can use form helpers or HTML.
推荐答案
tl;dr: 在 students
之后添加空括号 ([]
) 到输入名称.
摆弄 Rack::Utils.parse_nested_query 似乎你可以像这样获得你想要的有效载荷:
tl;dr: Add empty brackets ([]
) after students
to the input names.
Fiddling with Rack::Utils.parse_nested_query it seems you can get the payload you want like this:
<!-- first student -->
<input type="text" name="students[][first]">
<input type="text" name="students[][last]">
<input type="text" name="students[][age]">
<!-- second student -->
<input type="text" name="students[][first]">
<input type="text" name="students[][last]">
<input type="text" name="students[][age]">
注意 students
后面的空括号 ([]
). 这告诉 Rack 你想要 students
参数成为一个数组.遇到的后续参数(具有相同名称)将开始一个新元素.
Note the empty brackets ([]
) after students
. This tells Rack you want the students
param to be an array. Subsequent params encountered (with the same name) will start a new element.
POST/myroute?students[][first]=foo&students[][last]=bar&students[][age]=21&students[][first]=baz&students[][last]=qux&students[][age]=19
解析如下:
{"students" => [
{
"first" => "foo",
"last" => "bar",
"age" => "21"
},
{
"first" => "baz",
"last" => "qux",
"age" => "19"
}
]}
进一步阅读:http://codefol.io/posts/How-Does-Rack-Parse-Query-Params-With-parse-nested-query
这篇关于HTML 表单:POST 一个对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!