我正在使用数据表。我有一个包含多个输入的表,我想通过 ajax 将对象数组发布到 Controller 。
var data = table.$('input, select').serialize();
结果:
row-1-location=123&row-1-lot=231545&row-2-location=2323&row-2-lot=5523&row-3-location=23232&row-3-lot=23235
我假设我需要在每秒 '&' 处拆分字符串,然后再次拆分。 问题是,这是将其转换为对象数组的唯一方法吗?
我想要的结果是对象数组:
[{location : 123, lot: 231545}, {location: 2323, lot: 5523}......]
HTML:
<tbody>
<tr role="row" class="odd">
<td><input type="text" id="row-5-location" name="row-5-location" value=""></td>
<td><input type="text" id="row-5-lot" name="row-5-lot" value=""></td>
</tr>
<tr role="row" class="even">
<td><input type="text" id="row-6-location" name="row-5-location" value=""></td>
<td><input type="text" id="row-6-lot" name="row-5-lot" value=""></td>
</tr>
</tbody>
谢谢!
最佳答案
要创建所需的对象数组,直接从 DOM 构建结构而不是序列化它,然后分离结果字符串会更有意义。
为此,您可以选择父 tr
元素,然后使用 map()
构建对象。唯一可以使其更简单的 HTML 更改是将通用类放在 input
元素上。像这样:
var arr = $('table tr').map(function() {
var $tr = $(this);
return {
location: $tr.find('.location').val(),
lot: $tr.find('.lot').val()
}
}).get();
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr role="row" class="odd">
<td><input type="text" class="location" id="row-5-location" name="row-5-location" value="123"></td>
<td><input type="text" class="lot" id="row-5-lot" name="row-5-lot" value="231545"></td>
</tr>
<tr role="row" class="even">
<td><input type="text" class="location" id="row-6-location" name="row-5-location" value="2323"></td>
<td><input type="text" class="lot" id="row-6-lot" name="row-5-lot" value="5523"></td>
</tr>
</tbody>
</table>
关于javascript - 将 serialize() 转换为对象数组以发布到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56363477/