javascript 来自 Ajax 源的数据表按数据顺序排序并显示格式化日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34081205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:12:56  来源:igfitidea点击:

DataTables from Ajax source order-by data-order and display formatted date

javascriptjquerydatatablesdatatables-1.10

提问by Nicekiwi

Basically I want to pull data from ajax into my columns, but I want the cells in the columns to have the data-orderattribute on them with the value from the ajax call and use moment.js to format the data in the cell.

基本上,我想将数据从 ajax 提取到我的列中,但我希望列中的单元格具有data-order来自 ajax 调用的值的属性,并使用 moment.js 来格式化单元格中的数据。

I'm assuming this is the best way to make it pretty AND orderable. I found the plugin for datetime-momentJS, but it will only order the date, not format it as well.

我假设这是使其美观且可订购的最佳方式。我找到了 datetime-momentJS 的插件,但它只会对日期进行排序,而不会对其进行格式化。

var dataTable = $('#products').DataTable( {
  'processing': true,
  'ajax': '/products',
  'columns': [
    {
      'data': 'updated_at',
      'className':'date'
    }
  ]
});

right now I have this as the final result:

现在我把这个作为最终结果:

<td class="date">2015-11-08T11:00:00.000Z</td>

but the result I want is:

但我想要的结果是:

<td class="date" data-order="2015-11-08T11:00:00.000Z">11/08/2015</td>

Can I use the renderoption to do this somehow?

我可以使用该render选项以某种方式执行此操作吗?

The moment code to format it like I want would be moment('2015-11-08T11:00:00.000Z').format('DD/MM/YY').

像我想要的那样格式化它的时刻代码是moment('2015-11-08T11:00:00.000Z').format('DD/MM/YY').

采纳答案by Yeldar Kurmangaliyev

You can use createdRowcallback in order to apply any custom logics after row creation:

您可以使用createdRow回调来在行创建后应用任何自定义逻辑:

$('#products').dataTable({
  /* */
  'createdRow': function(row, data, dataIndex) {
      var $dateCell = $(row).find('td:eq(0)'); // get first column
      var dateOrder = $dateCell.text(); // get the ISO date
      $dateCell
          .data('order', dateOrder) // set it to data-order
          .text(moment(dateOrder).format('DD/MM/YY')); // and set the formatted text
  }
});

Note that td:eq(0)selector assumes that the column with date is the first column. You need to change 0 to another value, if it's not.

请注意,td:eq(0)选择器假定带有日期的列是第一列。如果不是,您需要将 0 更改为另一个值。

回答by Bogdan

You can achieve the same result directly by sending orthogonal datathrough Ajax.

您可以通过 Ajax发送正交数据直接获得相同的结果。

The timestamp formatting you will be doing on server side and you won't need any other JavaScript callbacks and plugins.

您将在服务器端进行时间戳格式化,并且不需要任何其他 JavaScript 回调和插件。

Code sample form the link above

代码示例来自上面的链接

JavaScript:

JavaScript:

$(document).ready(function() {
    $('#example').DataTable( {
        ajax: "data/orthogonal.txt",
        columns: [
            { data: "name" },
            { data: "position" },
            { data: "office" },
            { data: "extn" },
            { data: {
                _:    "start_date.display",
                sort: "start_date.timestamp"
            } },
            { data: "salary" }
        ]
    } );
} );

Ajax:

阿贾克斯:

{
  "data": [
    {
      "name": "Tiger Nixon",
      "position": "System Architect",
      "salary": "0,800",
      "start_date": {
        "display": "Mon 25th Apr 11",
        "timestamp": "1303686000"
      },
      "office": "Edinburgh",
      "extn": "5421"
    },
    {
    ...
    }
}

回答by Rob

I faced a very similar issue with a Laravel-based project of mine. Bogdan's answergot me on the right track; however, this link managed to help me completely solve my particular issue - https://www.gyrocode.com/articles/laravel-datatables-and-sortable-datetime-carbon-objects/.

我在我的基于 Laravel 的项目中遇到了非常相似的问题。Bogdan 的回答让我走上了正轨;但是,此链接设法帮助我完全解决了我的特定问题 - https://www.gyrocode.com/articles/laravel-datatables-and-sortable-datetime-carbon-objects/

The author is using yajra/laravel-datatablespackage for back-end processing - it is a fantastic package, and one I enjoy using. The official link for the DataTables JQuery plugin is https://datatables.net(you can also install this with Bowerand Node Package Manager). I am yet to explore DataTables in depth; however, there are numerous add-ons that DataTables also provides for extra functionality.

作者正在使用yajra/laravel-datatables包进行后端处理 - 这是一个很棒的包,我喜欢使用它。DataTables JQuery 插件的官方链接是https://datatables.net(您也可以使用BowerNode Package Manager安装它)。我还没有深入探索 DataTables;但是,DataTables 还提供了许多附加功能以提供额外功能。

In the author's example, he wanted to display his dates in a human-readable format, yet be able to sort it by a sortable value (e.g. a numerical value for a timestamp).

在作者的示例中,他希望以人类可读的格式显示他的日期,但能够按可排序的值(例如时间戳的数值)对其进行排序。

Below are code samples taken directly from source:

以下是直接取自源代码的代码示例:

PHP Code in his Laravel controller

他的 Laravel 控制器中的 PHP 代码

public function indexData()
{
    $users = User::select(['id', 'name', 'email', 'created_at']);

    return Datatables::of($users)
        ->editColumn('created_at', function ($user) {
           return [
              'display' => e(
                 $user->created_at->format('m/d/Y')
              ),
              'timestamp' => $user->created_at->timestamp
           ];
        })
        ->filterColumn('created_at', function ($query, $keyword) {
           $query->whereRaw("DATE_FORMAT(created_at,'%m/%d/%Y') LIKE ?", ["%$keyword%"]);
        })
        ->make(true);
}

Here, the author is adding 'display' and 'timestamp' values to be included with each 'created_at' data value. For the 'display' value, he is altering the created_at data value in a human-friendly format. The 'timestamp' value is a numerical representation of the created_at data value - this is the value the author plans to sort the data on.

在这里,作者添加了要包含在每个“created_at”数据值中的“display”和“timestamp”值。对于“显示”值,他正在以人性化的格式更改 created_at 数据值。'timestamp' 值是 created_at 数据值的数字表示 - 这是作者计划对数据进行排序的值。

Example JSON-formatted data

JSON 格式数据示例

The below sample of data is an example of what could be returned from the above controller:

下面的数据示例是可以从上述控制器返回的示例:

{   
    "draw": 1,
    "recordsTotal": 1,
    "recordsFiltered": 1,
    "data": [
        {
            "id":         "1",
            "name":       "Tiger Nixon",
            "email":      "[email protected]",
            "created_at": {
                "display": "12/31/2016",
                "timestamp": "1483142400"
            }
        }
    ]
}

Here, you can see 'display' and 'timestamp' values for the 'created_at' piece of data. As in Bogdan's answer, and mentioned earlier, the display value is for viewing by the user, and the 'timestamp' value is for sorting by the DataTables front-end.

在这里,您可以看到“created_at”数据的“display”和“timestamp”值。正如在 Bogdan 的回答中所提到的,显示值供用户查看,“时间戳”值供DataTables 前端排序。

DataTables Plugin Usage

数据表插件使用

To process the JSON-formatted data, the author has set-up the plugin as follows:

为了处理JSON格式的数据,作者设置了插件如下:

$('#users-table').DataTable({
    processing: true,
    serverSide: true,
    ajax: '/app/users',
    columns: [
        { data: 'id', name: 'id' },
        { data: 'name', name: 'name' },
        { data: 'email', name: 'email' },
        {
           data: 'created_at',
           type: 'num',
           render: {
              _: 'display',
              sort: 'timestamp'
           }
        }
    ]
});

Note: the author is using an AJAX call to retrieve his data in this example. You can replace ajax: '/app/users'to data: yourJsonData- using a variable which holds JSON data you want to process. The JSON data has been formatted specifically for use with DataTables.

注意:作者在此示例中使用 AJAX 调用来检索他的数据。您可以替换ajax: '/app/users'data: yourJsonData- 使用保存要处理的 JSON 数据的变量。JSON 数据经过专门格式化以用于 DataTables。

Orthogonal data, with respect to DataTables, has solved quite a few future problems for me in a project I'm working on. I can see this as being very powerful, especially for usability and being practical. I hope Bogdan's answer and this example helps any future readers out there - I'm certainly glad I came across them :).

就 DataTables 而言,正交数据已经为我在我正在从事的项目中解决了很多未来的问题。我认为这非常强大,尤其是在可用性和实用性方面。我希望 Bogdan 的回答和这个例子能帮助任何未来的读者 - 我当然很高兴遇到他们:)。