javascript - 将 serialize() 转换为对象数组以发布到 Controller

标签 javascript json asp.net-mvc serialization datatables

我正在使用数据表。我有一个包含多个输入的表,我想通过 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/

相关文章:

javascript - 从 Javascript 正确导航到 React 路由

javascript - 为什么 GET 响应返回 Node 服务器 js 的 404 错误?

javascript - Reddit 搜索 API 网址?

html - 将 CheckBox 和 Label 放在同一行 MVC

c# - 在 Asp.Net 应用程序中应该运行多少个工作流运行时?

javascript - Reactjs:在onClick方法中传递参数而不损失性能

javascript - jQuery - 如何动态打印空表

android - 在 onCreate 之前将来自 mySQL 的信息放入 Fragment textView 中

asp.net-mvc - 从扩展 Apicontroller 的 MVC Controller 返回 Json

asp.net-mvc - 在 ASP.NET MVC 中的回发之间持久化复杂数据