发布要形成的 n 个项目的数组
POSTing an array of n items to form
我想将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;
});
});
您想将数据
格式化JSON
以 POST 到您的表单中?
您的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;
}
相关文章:
- 有没有一种方法可以添加相同的项目val=“0”;4〃;到JavaScript中数组的每个对象
- 按不同项目对对象数组进行排序
- 使用JavaScript或jQuery检查单选按钮选择是否与数组中的项目匹配
- JS:从整个数组中每次得到5个项目,并得到平均值
- 使用圆中的数组更改背景颜色项目
- 编辑CSV数组中的项目-快速CSV node.js
- 我可以限制我添加到数组中的项目数量吗
- 使用javascript/jquery从现有数组中创建一个新数组,该数组保存项目存在的次数
- 什么's JavaScript数组中项目的作用域
- 将项目放入数组中
- 使用 id 和 Javascript 从数组中删除项目
- (角度.js)如何通过过滤器计算数组中有多少项目
- 如何通过迭代对象数组来删除某些项目
- Lodash 从与值数组不匹配的数组中获取项目
- 发布要形成的 n 个项目的数组
- 查找数组中项目包含子字符串的索引
- 使用节点在 JSON 数组中搜索项目(最好不迭代)
- Javascript:从数组中删除包含带有侦听器的对象的项目的最佳方法
- 更新挖空中可观察数组中项目的属性
- JavaScript:如何在 for 循环期间跳过数组中的当前项目?(继续?