【问题标题】:Is there a way to POST a group of form input fields as an object array?有没有办法将一组表单输入字段作为对象数组发布?
【发布时间】:2020-01-09 09:27:40
【问题描述】:

我正在向 HTML 表单动态添加一组输入并发布此表单,并希望将表单数据表示为对象数组

我有这个用户可以克隆的 HTML 表单输入组,并且另一个重复的输入组被添加到表单中:

<div class="questions entry input-group col-xs-3">
  <input class="form-control" id="clue" name="questions[clue][]" type="text" placeholder="Enter Clue" />
  <input class="form-control" id="answer" name="questions[answer][]" type="text" placeholder="Enter Clue Answer" />
  <input class="form-control" id="hint1" name="questions[hint1][]" type="text" placeholder="Optional: Enter a hint" />
  <input class="form-control" id="hint2" name="questions[hint2][]" type="text" placeholder="Optional: Enter a second hint" />
  <button class="btn btn-success btn-add" type="button">
    <i class="fas fa-plus"></i>
  </button>
</div>

在 POST 时,表单数据表示如下:

questions: { 
  clue: [ 'clue_a', 'clue_b' ],
  answer: [ 'answer_a', 'answer_b' ],
  hint1: [ 'hint_a1', 'hint_b1' ],
  hint2: [ 'hint_a2', 'hint_b2' ] 
}

但是,我想要更多类似以下的内容:

questions: [ 
  question: {
    clue:   'clue_a',
    answer: 'answer_a',
    hint1:  'hint_a1',
    hint2:  'hint_a2'
  },
  question: {
    clue:   'clue_b',
    answer: 'answer_b',
    hint1:  'hint_b1',
    hint2:  'hint_b2'
  }
}

【问题讨论】:

  • questions[0][clue], questions[1][clue], ... 可以解决问题,那么你需要一个计数器变量。
  • 我认为您遗漏了一些信息。 HTML 并不真正关心结构。它发布名称+值对。您如何获得当前示例?你真的在使用 jQuery 吗?您要发布到哪种类型的后端?
  • 请为后端语言添加标签,例如 C#、Python、Php 等
  • 我正在使用 express 发布到节点后端,这是要在服务器上输出的代码:router.post('/creategame', (req, res) =&gt; {console.log(req.body)}
  • @RolandStarke 我会试一试,但想知道是否有任何选择不必保留柜台?

标签: jquery html arrays node.js forms


【解决方案1】:

如果要按问题对它们进行排序,则需要将[]按正确顺序放入名称中:

name="questions[0][clue]"

……等等。

【讨论】:

  • 尝试name="questions[][clue]" 我得到以下结构,但线索对象不应该是数组questions: [ { clue: [Array], answer: [Array], hint1: [Array], hint2: [Array] } ] }
  • questions[0][clue], questions[1][clue] 使用计数器变量成功了
猜你喜欢
  • 1970-01-01
  • 2016-09-18
  • 1970-01-01
  • 2017-12-02
  • 1970-01-01
  • 2019-08-26
  • 2020-02-22
  • 2021-05-17
  • 2012-02-26
相关资源
最近更新 更多