最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use jQuery Datatable plugin from rest api json? - Stack Overflow

programmeradmin5浏览0评论

I want to get all the json from /?format=json data using REST API & jQuery plugin DataTable, but my problem is, it loads the data at first, but when I start typing in the search field provided by Datatable .. it says "No data available in table".

I've been searching this similiar problem, but I still can't find the solution. What I have tried is

My HTML file:

rest.html


<table id="tableSwapi" class="table table-striped">
         <thead>
            <tr>
                <th>Name</th>
                <th>Rotation Period</th>
                <th>Orbital Period</th>
                 <th>Diameter</th>
                 <th>Climate</th>
                 <th>Gravity</th>
                 <th>Terrain</th>
                 <th>Water Surface</th>
                 <th>Population</th>
            </tr>
         </thead>
         <tbody id="list-list">

         </tbody>
</table>

My script file:

script.js

$(document).ready(function () {
 $("#tableSwapi").dataTable();

$.ajax({
        url: '/',
        type: 'get',
        dataType: 'json',
        success: function (result) {
            let daftar = result.results;
            var html = '';
            $.each(daftar, function (i, data) {             
                html += `<tr>
                            <td> ` + data.name + `</td>
                            <td>` + data.rotation_period + `</td>
                            <td>` + data.orbital_period + `</td>
                            <td>` + data.diameter + `</td>
                            <td> ` + data.climate + ` </td>
                            <td> ` + data.gravity + ` </td>
                            <td>` + data.terrain + `</td>
                            <td> ` + data.surface_water + `</td>
                            <td> ` + data.population + ` <br></td>
                        </tr>`;

                //This is selector of my <tbody> in my table
                $("#list-list").html(html);
            });
        }
    });
})

Any kind of help is appreciated. Thank you.

I want to get all the json from https://swapi.co/api/planets/?format=json data using REST API & jQuery plugin DataTable, but my problem is, it loads the data at first, but when I start typing in the search field provided by Datatable .. it says "No data available in table".

I've been searching this similiar problem, but I still can't find the solution. What I have tried is

My HTML file:

rest.html


<table id="tableSwapi" class="table table-striped">
         <thead>
            <tr>
                <th>Name</th>
                <th>Rotation Period</th>
                <th>Orbital Period</th>
                 <th>Diameter</th>
                 <th>Climate</th>
                 <th>Gravity</th>
                 <th>Terrain</th>
                 <th>Water Surface</th>
                 <th>Population</th>
            </tr>
         </thead>
         <tbody id="list-list">

         </tbody>
</table>

My script file:

script.js

$(document).ready(function () {
 $("#tableSwapi").dataTable();

$.ajax({
        url: 'https://swapi.co/api/planets/',
        type: 'get',
        dataType: 'json',
        success: function (result) {
            let daftar = result.results;
            var html = '';
            $.each(daftar, function (i, data) {             
                html += `<tr>
                            <td> ` + data.name + `</td>
                            <td>` + data.rotation_period + `</td>
                            <td>` + data.orbital_period + `</td>
                            <td>` + data.diameter + `</td>
                            <td> ` + data.climate + ` </td>
                            <td> ` + data.gravity + ` </td>
                            <td>` + data.terrain + `</td>
                            <td> ` + data.surface_water + `</td>
                            <td> ` + data.population + ` <br></td>
                        </tr>`;

                //This is selector of my <tbody> in my table
                $("#list-list").html(html);
            });
        }
    });
})

Any kind of help is appreciated. Thank you.

Share Improve this question edited Mar 23, 2019 at 10:52 Ibrahim Ahmad asked Mar 23, 2019 at 10:11 Ibrahim AhmadIbrahim Ahmad 1091 silver badge8 bronze badges 4
  • 1 Would be better to insert the data itself through Datatable API then tell it to redraw. If you insert html yourself the plugin has no idea anything has changed. It stores the table state internally in order to know what rows to render based on sort, pagination , search etc – charlietfl Commented Mar 23, 2019 at 10:16
  • Where are you initializing datatable in your code? – prinkpan Commented Mar 23, 2019 at 10:52
  • I'm sorry, i just edited the script code. there you go. – Ibrahim Ahmad Commented Mar 23, 2019 at 10:53
  • @charlietfl ok thanks, i've figured it out, so i went to load the ajax first and second I loaded the DataTable() inside the setTimeout() function, so the I gave the time to let the DataTable knows if there are data rows in the table. – Ibrahim Ahmad Commented Mar 24, 2019 at 5:40
Add a ment  | 

2 Answers 2

Reset to default 3

If you can use server side script then try the code like

PHP Code ajax.php

$url = "https://swapi.co/api/planets/?page=".($_GET['start']/$_GET['length']+1); 
if (isset($_GET['search']) && !empty($_GET['search'])) {
    $url .= "&search=".$_GET['search']['value'];
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_URL, $url);
$result = json_decode(curl_exec($ch),true);
$array = array
        (
            "draw" => $_GET['draw'],
            "recordsTotal" => $result['count'],
            "recordsFiltered" => $result['count'],
            "data" => $result['results'],
        );
echo json_encode($array);

Jquery Datatable Code

$('#tableSwapi').DataTable({
    "processing": true,
    "serverSide": true,
    "sPaginationType": "full_numbers",
    "order": [],
    "ajax": {
        "url": "ajax.php",
        "type": 'get',
        "dataType": 'json'
    },
    "columns": [
        { "data": "name" },
        { "data": "rotation_period" },
        { "data": "orbital_period" },
        { "data": "diameter" },
        { "data": "climate" },
        { "data": "gravity" },
        { "data": "terrain" },
        { "data": "surface_water" },
        { "data": "population" },
    ]
});

I used your example and it's working properly.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn./bootstrap/3.4.0/css/bootstrap.min.css">
    <link href="https://cdn.datatables/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
    
</head>
<body>
    <table id="tableSwapi" class="table table-striped">
        <thead>
            <tr>
                <th>Name</th>
                <th>Rotation Period</th>
                <th>Orbital Period</th>
                <th>Diameter</th>
                <th>Climate</th>
                <th>Gravity</th>
                <th>Terrain</th>
                <th>Water Surface</th>
                <th>Population</th>
            </tr>
        </thead>
        <tbody id="list-list"></tbody>
    </table>    
    <script
  src="http://code.jquery./jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
    <script src="https://cdn.datatables/1.10.19/js/jquery.dataTables.min.js"></script>
    
    <script>
        $(document).ready(function () {
            $("#tableSwapi").dataTable();

            $.ajax({
                url: 'https://swapi.co/api/planets/',
                type: 'get',
                dataType: 'json',
                success: function (result) {
                    let daftar = result.results;
                    var html = '';
                    $.each(daftar, function (i, data) {
                        html += `<tr>
                                        <td> ` + data.name + `</td>
                                        <td>` + data.rotation_period + `</td>
                                        <td>` + data.orbital_period + `</td>
                                        <td>` + data.diameter + `</td>
                                        <td> ` + data.climate + ` </td>
                                        <td> ` + data.gravity + ` </td>
                                        <td>` + data.terrain + `</td>
                                        <td> ` + data.surface_water + `</td>
                                        <td> ` + data.population + ` <br></td>
                                    </tr>`;

                        //This is selector of my <tbody> in my table
                        $("#list-list").html(html);
                    });
                }
            });
        })


    </script>
</body>
</html>

Maybe a problem with Datatable plugin. Please check in inspect elements.

发布评论

评论列表(0)

  1. 暂无评论