Jquery DataTables AJAX默认排序不起作用

时间:2015-04-09 20:39:24

标签: jquery ajax json datatables datatables-1.10

我正在拉入原始JSON来填写我的DataTable。

问题是像分页和排序这样的东西不起作用。

我不是从数据库中提取信息,我实际上是从AWS提取数据。

来自AWS - >缓存文件 - > JSON - >数据表。

我的JSON看起来像这样:

{
"count": 332,
"data": [
  {
  "account": "NetOps",
  "architecture": "x86_64",
  "block_devices": [
    {
      "delete_on_terminate": true,
      "name": "/dev/sda1",
      "status": "attached",
      "volume_id": "vol-secret"
    }
  ],
  "ebs_optimized": false,
  "group_name": null,
  "hypervisor": "xen",
  "id": "i-secret",
  "instance_type": "m1.small"}
]} 

当然,真实结果会返回323条记录......

根据JSON Lint

,JSON是有效的JSON

以下是我用于DataTables的内容:

<script>
  $(document).ready(function() {
  $('#ec2_table').DataTable({
            "serverSide": true,
            "ajax": '/ec2',
            "columns": [
        { "data": "id" },
        { "data": "name" },
        { "data": "architecture" },
        { "data": "instance_type" },
        { "data": "image_id" },
        { "data": "platform" },
        { "data": "state" },
        { "data": "account" },
                    ],
         "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
            dom: 'T<"clear">lfrtip',
            tableTools: {
        "sSwfPath":    "/static/js/DataTables/extensions/TableTools/swf/copy_csv_xls_pdf.swf"
    }
    });
});

</script>

分页,列排序,搜索都不起作用。

我的Jinja / HTML看起来像这样:

<table id="ec2_table" class="order-column display compact" cellspacing="0"    width="98%">
  <thead>
    <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Architecture</th>
          <th>InstType</th>
          <th>Image ID</th>
          <th>Platform</th>
          <th>State</th>
          <th>Account</th>
    </tr>
  </thead>
</table>

1 个答案:

答案 0 :(得分:2)

我一直在查看dataTables文档,我认为问题出在您的JSON上。

server-side manual

这是他们给出的例子。 count:不是数据表所需的列出参数之一。如果更改JSON以返回“draw”,请告诉我。 “recordsTotal”,“recordsFiltered”和“data”作为参数有效。因为我自己还在学习DataTables。

{
"draw": 1,
"recordsTotal": 57,
"recordsFiltered": 57,
"data": [
    [
        "Angelica",
        "Ramos",
        "System Architect",
        "London",
        "9th Oct 09",
        "$2,875"
    ],
    [
        "Ashton",
        "Cox",
        "Technical Author",
        "San Francisco",
        "12th Jan 09",
        "$4,800"
    ],
    ...
]

}

我终于完成了所有这些工作!

你需要这个类来为ajax / json播放api

Imports System.Web.Script.Serialization

Public Class DataTableJsonModel
    Public Property draw As Integer
    Public Property start As Integer
    Public Property length As Integer
    Public Property search As SearchModel
    Public Property order As OrderModel()
    Public Property columns As ColumnModel()

    Class ColumnModel
        Public Property Data As String
        Public Property Name As String
        Public Property searchable As Boolean
        Public Property Orderable As Boolean
        Public Property Search As SearchModel
    End Class

    Class SearchModel
        Public Property value As String
        Public Property regex As Boolean
    End Class

    Class OrderModel
        Public Const asc As String = "asc"
        Public Const desc As String = "desc"

        Public Property column As Integer
        Public Property dir As String
    End Class
End Class

Public Class DataTableReturnModel
    Public Property draw As Integer
    Public Property data As Object
    Public Property recordsTotal As Integer
    Public Property recordsFiltered As Integer
    Public Property errorMessage As String
End Class

Public Class AWS
    Public Property instance_type As String
    Public Property id As String
    Public Property architecture As String
    Public Property account As String
    Public Property name As String

    Public Property block_devices As BlockDeviceModel()
    Public Property ebs_optimized As Boolean
    Public Property group_name As String
    Public Property hypervisor As String


    Class BlockDeviceModel
        Public Property delete_on_terminate As Boolean
        Public Property name As String
        Public Property status As String
        Public Property volume_id As String
    End Class
End Class

我的Html / javascript看起来像这样。

@Code
    ViewData("Title") = "AWSDataTables"
End Code


<script>
    $(document).ready(function () {
        var table = $('#ec2_table').DataTable({
            "serverSide": true,
            "ajax": { url: '/Home/ec2',
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                data: function (d) {
                    return JSON.stringify(d);
                },
            },
            "columns": [
        { "data": "id" },
        { "data": "name" },
        { "data": "architecture" },
        { "data": "instance_type" },

            ],
            "lengthMenu": [[10, 25, 50, 100, 1000], [10, 25, 50, 100, 1000]],
            dom: 'T<"clear">lfrtip',
            tableTools: {
                "sSwfPath": "/Scripts/media/js/DataTables/extensions/TableTools/swf/copy_csv_xls_pdf.swf"
            }
        });
    });

</script>

<h2>AWSDataTables</h2>

<table id="ec2_table" class="order-column display compact" cellspacing="0" width="98%">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Architecture</th>
            <th>InstType</th>
        </tr>
    </thead>
</table>

我的服务器端控制器代码是这样的。

Function AWSDataTables() As ActionResult
    Return View()
End Function

<HttpPost()> _
Function ec2(d As DataTableJsonModel) As JsonResult
    Dim dataresults As IEnumerable(Of AWS) = GetAWSTestList()
    Dim filteredData As IEnumerable(Of AWS) = dataresults
    Dim output As New DataTableReturnModel()

    'sorting happens here
    If Not String.IsNullOrEmpty(d.Search.value) Then
        Dim s As String = d.search.value.ToLower
        'this will obviously change based on your class.
        filteredData = dataresults.Where(Function(x) x.id.ToLower.Contains(s) OrElse
                                             x.architecture.ToLower.Contains(s) OrElse
                                             x.name.ToLower.Contains(s))
    End If

    'Ordering happens here
    If Not IsNothing(d.order) AndAlso d.order.Length > 0 Then
        Dim orderM As DataTableJsonModel.OrderModel = d.order(0)
        If Not IsNothing(orderM) Then
            Dim sortDirection As String = orderM.dir
            Dim columnM As DataTableJsonModel.ColumnModel = d.columns.ElementAtOrDefault(orderM.column)
            If Not IsNothing(columnM) AndAlso Not String.IsNullOrEmpty(columnM.Data) AndAlso Not IsNothing(GetType(AWS).GetProperty(columnM.Data)) Then
                If sortDirection = DataTableJsonModel.OrderModel.asc Then
                    filteredData = filteredData.OrderBy(Function(x) GetType(AWS).GetProperty(columnM.Data).GetMethod.Invoke(x, {}))
                Else
                    filteredData = filteredData.OrderByDescending(Function(x) GetType(AWS).GetProperty(columnM.Data).GetMethod.Invoke(x, {}))
                End If
            End If
        End If
    End If

    output.data = filteredData.Skip(d.start).Take(d.length)
    output.recordsFiltered = filteredData.Count
    output.recordsTotal = dataresults.Count

    Return Json(output)
End Function