【问题标题】:Loading JSON into data tables将 JSON 加载到数据表中
【发布时间】:2014-12-09 17:58:02
【问题描述】:

我有一个使用 ASP.NET MVC 构建的 Web API。访问该 API 的结果如下所示:

{
  "RequestID":1,
  "Options": [
    {"Id":"A", "Name":"Alpha"},
    {"Id":"B", "Name":"Bravo"}
  ],
  "Responses":[
    {"Id":123, "Name":"Test 1", "Description":"This is the first response"},
    {"Id":222, "Name":"Test 2", "Description":"This is the second response"},
    {"Id":333, "Name":"Test 3", "Description":"This is the third response"},
  ]
}

我想使用DataTables plugin 将 Web API 的响应加载到数据表中。为了做到这一点,我有以下几点:

<head>
  <script type="text/javascript" src="//code.jquery.com/jquery-1.11.1.min.js"></script>
  <script type="text/javascript" src="//cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js"></script>
</head>
<body>
    <table id="properties" class="table table-bordered">
        <thead>
            <tr>
                <th>ID</th>
                <th class="sortable">Name</th>
                <th>Description</th>
            </tr>
        </thead>
    </table>

    <script type="text/javascript">
        $(document).ready(function () {
            $('#properties').dataTable({
                "processing": true,
                "serverSide": true,
                "ajax": {
                    'url':'/api/Search?query=Test'
                }
            });
        });
    </script>
</body>

我基于找到的示例here 的实现。我的问题是,它不起作用。就像数据表不知道将 Responses 属性用作数据表的数据集一样。但是,我不知道如何设置它。

有人知道我如何将Responses 数组中的对象加载到数据表中吗?

谢谢!

【问题讨论】:

    标签: jquery asp.net datatable


    【解决方案1】:

    为了让 DataTables 显示您的数据,必须以 DataTables 可以理解的方式对其进行格式化。请参阅http://datatables.net/manual/server-side 以获取参考。查看标题返回的数据

    具体来说,您的 JSON 需要将数据放在名为 data 的参数下(而不是 Responses)。

    您还需要包含 drawrecordsTotalrecordsFildered 参数。

    如果您无法修改 Web API 以适应 DataTables 格式,则需要使用另一种方法。想到的两个是编写一个中间服务,将 Web API 的输出转换为 DataTables 的正确格式,或者使用 JavaScript 手动读取 Web API 的输出并将行插入到您的表中。

    【讨论】:

      【解决方案2】:

      你可以试试这个:

      由于无法访问您的 API,我无法验证以下内容。但它应该可以正常工作。

      <script type="text/javascript">
          $(document).ready(function () {
              $('#properties').dataTable({
                  "processing": true,
                  "serverSide": true,
                  "ajax": {
                      'url':'/api/Search?query=Test',
                      "dataSrc": "Responses"
                  }
              });
          });
      </script>
      

      谢谢!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-15
        相关资源
        最近更新 更多