将DataTable请求中的列数据转换为数组

问题描述 投票:0回答:1

这适用于 Express.js 版本 4.18.2 Web 应用程序。该 Web 应用程序提供一个包含

<table>
的 HTML 页面,我使用 DataTables jQuery 插件使表格更加精美。

客户端

在 HTML 页面中,DataTable 配置为使用服务器端处理,并且还定义了表的列。

<html>
<body>
  ...
  <table id="person_table">
    <thead>
      <th>Name</th>
      <th>Phone</th>
    </thead>
    <tbody>
    </tbody>
  </table>
  ...

  <script>
    $( document ).ready( function ()
    {
      var config = {};

      // Define columns.
      var c = 0;
      config.columnDefs = [];
      config.columnDefs.push( { targets: c++, data: "name", name: "name" } );
      config.columnDefs.push( { targets: c++, data: "phone", name: "phone" } );

      // Server side processing mode.
      config.serverSide = true;

      // Load records from an Ajax source, i.e., the server.
      config.ajax =
      {
        // The URL to which the request is sent.
        url: '/person/load',

       // Send an HTTP post request.
       type: 'POST',
      };

      // Create the DataTable.
      $( '#person_table' ).DataTable( config );
    } );
  </script>
</body>
</html>

服务器端

当Web应用程序收到来自DataTable的加载记录的请求时,DataTable特定数据的格式如下。

request: <ref *2> IncomingMessage {
  ...
  body: [Object: null prototype] {
    draw: '1',
    'columns[0][data]': 'name',
    'columns[0][name]': 'name',
    'columns[0][searchable]': 'true',
    'columns[0][orderable]': 'true',
    'columns[0][search][value]': '',
    'columns[0][search][regex]': 'false',
    'columns[1][data]': 'phone',
    'columns[1][name]': 'phone',
    'columns[1][searchable]': 'true',
    'columns[1][orderable]': 'true',
    'columns[1][search][value]': '',
    'columns[1][search][regex]': 'false',
    'order[0][column]': '0',
    'order[0][dir]': 'asc',
    start: '0',
    length: '10',
    'search[value]': '',
    'search[regex]': 'false'
  },
  ...
}

表中各列的数据是“扁平”的。即,有多个“columns[i][属性名称]”条目,而不是包含列数据的对象数组。

我可以不厌其烦地自己解析列数据并将其转换为对象数组。然而,https://datatables.net/manual/server-side说:

在大多数现代服务器端脚本环境中,该数据[即 订单和列数据]将自动为您提供 数组。

问题

Express.js 或 Node.js 中是否有某些东西可以自动将列数据转换为对象数组?

javascript express datatables
1个回答
0
投票

问题的解决方案是将 URL 编码主体解析器的扩展标志设置为 true 而不是 false。

例如,在 Express Web 应用程序的主 Javascript 文件中:

const BodyParser = require( 'body-parser' );
const Express = require( 'express' );

const app = Express();

// It is important for the extended flag to be true,
// so that the array and object data in an HTTP request is not flattened. 
app.use( BodyParser.urlencoded( { extended: true } ) );

...
© www.soinside.com 2019 - 2024. All rights reserved.