从rest api查询数据表而不用预先定义html中的表 [英] Query datatable from rest api without pre-defining the table in html

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

问题描述

我想通过来自 rest API 的 post 请求查询 JSON:

http://localhost/post1参数 1='1'

返回以下内容:

<代码>{json_table":[{日期":123,测试":你好2"},{日期":19,测试":你好"},}

然后它应该被自动填充到 jquery 数据表中,有点如何在此处描述:

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

我不明白的是:

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

感谢任何建议.

解决方案

从任意 JSON 创建动态 DataTable 当然是可能的 - 但它可能会变得复杂,具体取决于您尝试使用的 DataTables 的多少功能.

>

此外,如果您可以控制从服务器发送的 JSON,您可以让事情变得更简单.我假设您确实对以下内容有这种控制.

静态示例

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

服务器发送此 JSON 数据:

<代码>{数据": [{"id": "1","name": "老虎尼克松","position": "系统架构","salary": "$320,800","开始日期": "2011/04/25","office": "爱丁堡","extn": "5421",切换":关闭"},{"id": "2","name": "加勒特温特斯","position": "会计师","salary": "$170,750","开始日期": "2011/07/25","office": "东京","extn": "1278",切换":开"}]}

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

<div style="margin: 20px;"><table id="example" class="display" style="width:100%"></table>

<script type="text/javascript">$(document).ready(function() {var table = $('#example').DataTable( {阿贾克斯":{"url": "http://localhost:7000/employees","dataSrc": "数据",类型":获取",},列": [{数据":名称","title": "姓名" },{数据":位置","title": "位置" },{数据":办公室","title": "办公室" },{数据":分机","title": "分机."},{数据":开始日期","title": "开始日期" },{数据":工资","title": "薪水" },]});});

增强 JSON

为了方便我们自己,我们可以增强从服务器发送的 JSON,以包含有关数据记录中列的元数据:

<代码>{回复": [{列": [{数据":名称","title": "姓名"},{数据":位置","title": "职位"},{"数据": "办公室","title": "办公室"},{数据":分机","title": "分机."},{数据":开始日期","title": "开始日期"},{"数据": "工资","title": "工资"}]},{数据": [{"id": "1","name": "老虎尼克松","position": "系统架构","salary": "$320,800","开始日期": "2011/04/25","office": "爱丁堡","extn": "5421",切换":关闭"},{"id": "2","name": "加勒特温特斯","position": "会计师","salary": "$170,750","开始日期": "2011/07/25","office": "东京","extn": "1278",切换":开"}]}]}

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

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

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

var tableData = [];var tableColumns = [];...$('#example').DataTable({数据":表数据,列":表列});

为了更灵活,ajax请求可以从DataTables中分离出来:

组装您需要的最简单方法是(我认为)编写数据表的硬编码版本 - 然后开始用动态创建的变量替换部分.

带参数的POST

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

type: "POST",//请求类型(注意 CORS!)data: { "foo": "bar" }//请求体(表单参数)

这意味着 ajax 请求将是一个 POST,并且在这种情况下将包含一个包含 foo=bar 的请求正文.你当然可以把你需要的东西放进去.这是标准表格数据.服务器会以它使用的任何标准方式(例如请求上下文表单参数)读取这些数据.

自动刷新

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

setInterval( 函数 () {console.log("重新加载");}, 2000 );//毫秒

最后一点 - 只是重申一下 - 这将无法处理您扔给它的任何 JSON.如果您无法控制 JSON 结构,那么一个有效负载与下一个负载之间可能存在太多差异.

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

希望对您有所帮助或至少给您一些提示.

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

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

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

that returns the following:

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

    },
}

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

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

What I don't understand is:

  • How can I tell it to make a post request with a parameter
  • How can I create the table without having to predefine it in HTML, so that it's completely agnostic what is returned from the JSON and just displays the table accordingly, whatever is within the 'json_table' record (which is generated from a pandas data frame df.to_json(orient='records')?
  • How can I make it refresh (query again) every 15 seconds and update the table?

Any suggestions are appreciated.

解决方案

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.

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.

Static Example

Assume we start with this simple static example:

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"
    }
  ]
}

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>

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"
        }
      ]
    }
  ]
}

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

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
} );

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.

POST with parameters

The above ajax example includes these lines:

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

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).

Auto-Refresh

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

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

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.

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.

By the way, there should generally be no need to use code which manipulates the DOM (e.g. building strings of HTML, or manipulating tags). That is counter to how DataTables is designed to work. You should instead be working with the DataTables object itself, wherever possible.

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

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆