发布要形成的 n 个项目的数组

POSTing an array of n items to form

本文关键字:项目 数组      更新时间:2023-09-26

我想将n个长度的数组发布到表单中。处理这个问题的最佳方法是什么?

该对象是一个时间表,其中包含一个日期和一个行数组。

线条具有持续时间、类别和注释字段。

我的表单有一个日期字段,还有一行开始,jQuery根据需要附加更多行。

我知道我需要以某种方式使用括号表示法,但我不知道如何考虑我嵌套了两个对象。

FWIW,应用程序端的事情在 Node 中.js和快递。

<form id="timesheet" method="POST" action="/timesheets">
  <label>date for timesheet</label>
  <input type="date" name="date"/><br/>
  <ol id="timesheet-list">
    <li>
      <input type="number" name="hours" min="0" value="0" step=".25"/>
      <input type="text" name="category"/>
      <input type="text" name="details"/>
    </li>
  </ol>
  <input type="submit"/>
</form>
<a id="addItem" href="#">Add a new line item</a>
<script type="text/javascript">
  $('#addItem').click(function(e){
    e.preventDefault();
    $('#timesheet-list').append('<li><input type="number"> <input type="text"> <input type="text"></li>');
  });
</script>

如果您想使用 jQuery serializeArray 方法将其作为 JSON 数据提交,我认为您可以序列化您的输入值

      $('form').submit(function() {
          alert($(this).serializeArray());
          return false;
      });

请注意,要使上述功能正常工作,您的<input ...>必须具有name属性。

对于可能希望将更复杂的数据(对象类型)编码为表单数据的其他人,这里的答案很有帮助。基本上,它使用 serializeArray 函数将其转换为 JavaScript 对象(包含以下代码,因为链接可能会随着时间的推移而处于非活动状态)

  $.fn.serializeObject = function()
  {
   var o = {};
   var a = this.serializeArray();
    $.each(a, function() {
       if (o[this.name] !== undefined) { //check to see if name attribute exists
           if (!o[this.name].push) { 
              o[this.name] = [o[this.name]];
           }
           o[this.name].push(this.value || '');
         } else {
            o[this.name] = this.value || ''; 
          }
    });
    return o;
 };

使用该函数

 $(function() {
     $('form').submit(function() {
         $('#result').text(JSON.stringify($('form').serializeObject()));
      return false;
    });
});​
您想将数据

格式化JSONPOST 到您的表单中?

您的JSON对象将如下所示。

// Entire object is a representation of a 'Timesheet'
{
  date: '8-8-2012',
  lines: [ // Array of objects, each storing a duration, catagory and note.
    {
      duration: 0,
      catagory: 'whatever',
      note: 'whatever'
    },
    { // Have as many of these as you please.
      duration: 123,
      catagory: 'another',
      note: 'moar notes'
    },
  ]
}

收到此对象后,可以按如下方式访问数据:

data = getTimesheet(); // Assume this function gets the above JSON
data.date;
for(var i=0; i<data.lines.length; i++) {
    data.lines[i].duration;
    data.lines[i].catagory;
    data.lines[i].note;
}