从rest api查询数据表,而无需在html中预定义表 [英] Query datatable from rest api without pre-defining the table in html

查看:36
本文介绍了从rest api查询数据表,而无需在html中预定义表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过rest API的发布请求查询JSON:

I would like to query a JSON via post request from a rest API:

http://localhost/post1  
param1='1'

返回以下内容:

{
  "json_table": [
    {
      "date": 123,
      "test": "hello2"
    },
    {
      "date": 19,
      "test": "hello"

    },
}

,然后应将其自动填充到jquery数据表中,有点像此处所述:

and it should then be automatcially populated into a jquery datatable, a little bit how it is described here:

$('#myTable').DataTable( {
    ajax: '/api/myData'
} );

我不明白的是:

  • 如何告诉它发出带有参数的发帖请求
  • 如何创建表而不必在HTML中预定义表,以使它完全不可知从JSON返回的内容,并仅显示表,无论"json_table"记录(由熊猫生成)中的任何内容数据框df.to_json(orient ='records')?
  • 如何使它每15秒刷新一次(再次查询)并更新表格?

任何建议都值得赞赏.

推荐答案

从任意JSON创建动态DataTable当然是可能的-但根据要使用的DataTable的许多功能,它可能会变得复杂.

Creating a dynamic DataTable from arbitrary JSON is certainly possible - but it can get complicated depending on how many of the features of DataTables you are trying to use.

此外,如果您可以控制从服务器发送的JSON,则可以使事情变得更轻松.我会假设您对此具有控制权.

Also, if you have control over the JSON being sent from the server, you can make things easier for yourself. I will assume you do have such control for what follows.

假设我们从这个简单的静态示例开始:

Assume we start with this simple static example:

服务器发送以下JSON数据:

The server sends this JSON data:

{
  "data": [
    {
      "id": "1",
      "name": "Tiger Nixon",
      "position": "System Architext",
      "salary": "$320,800",
      "start_date": "2011/04/25",
      "office": "Edinburgh",
      "extn": "5421",
      "toggle": "off"
    },
    {
      "id": "2",
      "name": "Garrett Winters",
      "position": "Accountant",
      "salary": "$170,750",
      "start_date": "2011/07/25",
      "office": "Tokyo",
      "extn": "1278",
      "toggle": "on"
    }
  ]
}

我们有一个简单的DataTables定义,如下所示:

And we have a simple DataTables definition like this:

<body>

<div style="margin: 20px;">

<table id="example" class="display" style="width:100%"></table>

</div>

<script type="text/javascript">

  $(document).ready(function() {

    var table = $('#example').DataTable( {
      "ajax": { 
        "url": "http://localhost:7000/employees",
        "dataSrc": "data",
        "type": "GET", 
      },
      "columns": [
        { "data": "name",
          "title": "Name" },
        { "data": "position",
          "title": "Position" },
        { "data": "office",
          "title": "Office" },
        { "data": "extn",
          "title": "Extn." },
        { "data": "start_date",
          "title": "Start Date" },
        { "data": "salary",
          "title": "Salary" },
      ]

    } );

  } );

</script>

</body>

增强JSON

为了使事情变得更容易,我们可以增强从服务器发送的JSON,以包含有关数据记录中列的元数据:

Enhancing the JSON

To make things easier for ourselves, we can enhance the JSON being sent from the server, to contain metadata about the columns in the data records:

{
  "response": [
    {
      "columns": [
        {
          "data": "name",
          "title": "Name"
        },
        {
          "data": "position",
          "title": "Position"
        },
        {
          "data": "office",
          "title": "Office"
        },
        {
          "data": "extn",
          "title": "Extn."
        },
        {
          "data": "start_date",
          "title": "Start Date"
        },
        {
          "data": "salary",
          "title": "Salary"
        }
      ]
    },
    {
      "data": [
        {
          "id": "1",
          "name": "Tiger Nixon",
          "position": "System Architext",
          "salary": "$320,800",
          "start_date": "2011/04/25",
          "office": "Edinburgh",
          "extn": "5421",
          "toggle": "off"
        },
        {
          "id": "2",
          "name": "Garrett Winters",
          "position": "Accountant",
          "salary": "$170,750",
          "start_date": "2011/07/25",
          "office": "Tokyo",
          "extn": "1278",
          "toggle": "on"
        }
      ]
    }
  ]
}

JSON中这个新的columns部分基本上与硬编码到第一个DataTables定义中的信息相同.

This new columns section in the JSON is basically the same information as was hard-coded into the first DataTables definition.

当我们从服务器接收JSON时,我们可以将其读入变量,然后在DataTables配置中使用此变量.

We can read that into a variable, when we receive the JSON from the server, and then use this variable in our DataTables configuration.

我们还可以对数据记录做同样的事情:

And we can do the same thing for the data records also:

var tableData = [];
var tableColumns = [];

...

$('#example').DataTable( {
  "data": tableData,
  "columns": tableColumns
} );

为了获得更大的灵活性,可以将ajax请求与DataTables分开:

For more flexibility, the ajax request can be separated out from DataTables:

<script type="text/javascript">

  var tableData = [];
  var tableColumns = [];

  function ajax1() {
    return $.ajax({
      url: "http://localhost:7000/employees",
      success : handleData,
      type: "POST",
      data: { "foo": "bar" }
    });
  }

  function handleData(data) {
    tableData = data.response[1].data;
    //console.log(JSON.stringify(tableData));
    tableColumns = data.response[0].columns;
  }

  $(document).ready(function() {

    $.when(ajax1()).done(function(a1){
      $('#example').DataTable( {
        "data": tableData,
        "columns": tableColumns
      } );

    });

  } );

</script>

(我认为)组装所需内容的最简单方法是编写数据表的硬编码版本,然后开始用动态创建的变量替换片段.

The easiest way to assemble what you need is (I think) to write the hard-coded version of your data table - and then to start replacing pieces with dynamically created variables.

上面的ajax示例包括以下几行:

The above ajax example includes these lines:

type: "POST",            // request type (watch out for CORS!)
data: { "foo": "bar" }   // request body (form parameters)

这意味着ajax请求将是一个POST,并且在这种情况下将包含一个包含foo=bar的请求正文.您当然可以在其中放置任何所需的东西.这是标准表格数据.服务器将以其使用的任何标准方式(例如,请求上下文形式参数)读取此数据.

This means the ajax request will be a POST and will contain a request body in this case containing foo=bar. You can, of course put whatever you need in there. It's standard form data. The server would read this data in whatever standard way it uses (e.g. request context form parameters).

我自己还没有做过,但是有些解决方案是使用setInterval记录的-像这样:

I haven't done this myself, but there are solutions documented using setInterval - something like this:

setInterval( function () {
  console.log("reloading");
}, 2000 ); // milliseconds

最后的记录-只是重申一下-这将无法处理您向其抛出的任何JSON.而且,如果您无法控制JSON结构,那么从一个有效负载到另一个有效负载的差异可能就太大了.

Final note - just to reiterate - this is not going to be able to handle whatever JSON you throw at it. And if you have no control over the JSON structures, then there may well be too many differences from one payload to the next.

但是,如果您控制JSON并且想要定义更多功能(例如,默认排序,隐藏列),则可以开始将这些功能作为其他元数据项添加到JSON中.

But if you control the JSON and if you want to define more features (e.g. default sorting, hidden columns) then you can start adding those to the JSON as additional metadata items.

希望能帮助或至少为您提供一些指导.

Hope that helps or at least gives you some pointers.

顺便说一句,通常不需要使用操纵DOM的代码(例如,构建HTML字符串或操纵标签).这与DataTables的工作方式背道而驰.相反,您应该尽可能使用DataTables对象本身.

这篇关于从rest api查询数据表,而无需在html中预定义表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆