以声明方式从嵌套JSON填充DataTable

时间:2018-03-23 12:45:18

标签: jquery datatables

我有一个返回以下JSON的API:

{ "data": [
    {
        "sensors": [
            {
                "description": "Second Sensor",
                "value": 6.0
            },
            {
                "description": "My Default Sensor",
                "value": 8.0
            }
        ],
        "timestamp": "2018-04-01T00:00:00"
    },
    {
        "sensors": [
            {
                "description": "Second Sensor",
                "value": 8.0
            },
            {
                "description": "My Default Sensor",
                "value": 6.0
            }
        ],
        "timestamp": "2018-03-31T23:59:59"
    }
] }

我想只渲染data[0]中的第一个元素DataTable

<table width="100%" class="table table-striped table-hover" id="dataTable">
    <thead>
        <tr>
            <th>Sensor</th>
            <th>Value</th>
        </tr>
    </thead>
</table>

我期待它显示:

Second Sensor          6.0
My Default Sensor      8.0

我可以使用DataTables以声明方式执行此操作,还是必须通过客户端JavaScript的API修改返回的数据,然后将其传递给DataTable

以下代码并不是我所寻求的,因为它始终只显示一个传感器。

$('#dataTable').DataTable({          
    ajax: 'myapiurl',
    columns: [
        { "data": "sensors.0.description" },
        { "data": "sensors.0.value" 
    ]
});

1 个答案:

答案 0 :(得分:0)

我提出了以下解决方案:

<?php
error_reporting(-1);              // Report all type of errors
ini_set("display_errors", 1);     // Display all errors
?>



<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
    <title>Guestbook</title>
</head>
<link rel="stylesheet" href="css/stilmall.css?<?php echo time(); ?>" type="text/css">
<body>

<nav id="mainmenu">
                <ul>
                    <li><a href="index.php">Home</a></li>
                    <li><a href="login.php">Administration</a></li>
                </ul>
            </nav>

<div class="posts">

<h3>Add post:</h3>


<?php 
    include("includes/config.php");


    $user = new Users();

    /*// Radera
    if(isset($_GET['deleteid'])) {
        $id = $_GET['deleteid'];

        if($user->deleteUser($id)) {
            echo "<p> Post Deleted</p>";
        } else {
            echo "<p> Error trying to delete post</p>";
        }
    }
        */
    // new post
    if(isset($_POST["submit"])) {
        $name = $_POST["name"];
        $post = $_POST["post"];

        if( $user->addUser($name, $post)) {
        echo("<p> Post added to board! </p>");
    } else {
        echo("<p> Error trying to add post to board </p>");
    }
    }




?>

<form method="post" action="index.php">
        Username: <input type="text" name="name">
        Content: <input type="text" name="post">
        <input type="submit" value="Add Post" name="submit">

</form>


<h3>Existing Posts</h3>

<?php
    //show posts

    $userlist = $user->getUsers();

    foreach($userlist as $c) {

        echo  $c["name"] . " - " . $c["post"] . "<br>" . "Posted: " . $c["postdate"] . "<br><br>";
    }
?>



</p>

</div>

</body>
</html>