DataTables警告:table id = dataTable - 无法重新初始化DataTable

时间:2018-01-20 00:31:06

标签: javascript jquery datatables

我正在使用数据表并尝试每隔几秒刷新传入的数据而不刷新页面。初始页面加载有效但在设置延迟后我收到错误“Datatables warning(table id ='example'):无法重新初始化数据表”。查看数据表网站以获取帮助,但找不到我的设置的任何特定内容。任何反馈意见。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Crypto Market Cap</title>
    <link rel="icon" type="image/png" href="imgs/favicon.ico" />
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
    <link rel="stylesheet" type="text/css" href="css/spritesheet.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-112760236-1"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'UA-112760236-1');
    </script>
    <style>
        #tableHeader tr td { font-weight:bold }
    </style>
</head>
<body>
    <img src="imgs/spritesheet.png" width="0" height="0" style="display: none">
    <div class="container">
        <div class="row" style="text-align:center;margin-bottom:30px">
            <h2 class="col-xs-12">
                Cryptocurrency Market Capitalizations
            </h2>
            <h5>$USD</h5>
        </div>
        <div class="row">
            <div class="col-xs-12" style="padding:0">
                <table id="dataTable" class="table table-bordered hover" style="margin:0 auto">
                    <thead id="tableHeader">
                        <tr>
                            <td>#</td>
                            <td>Name</td>
                            <td>Price</td>
                            <td>Market Cap</td>
                            <td>Available Supply</td>
                            <td>24 HR % Change</td>
                        </tr>
                    </thead>
                </table>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12" style="text-align:center;margin-top:50px">
                <img src="imgs/loading.gif" style="height:120px" id="loading">
            </div>
        </div>
    </div>
<script>
    function executeQuery() {
        $.ajax({
            url: "http://coincap.io/front",
            type: "GET",
            dataType: "json",
            success: function (data) {
                var items = [];
                var len = data.length;
                for (var i = 0; i < len; i++) {
                    var numFormat = data[i].price.toLocaleString("en");
                    var numFormat1 = data[i].mktcap.toLocaleString("en");
                    var numFormat2 = data[i].supply.toLocaleString("en");
                    var lowerCaseName = data[i].long.toLowerCase();
                    items.push("<tr><td>" + [i+1] + "</td><td> <span class='sprite sprite-" + lowerCaseName + " small_coin_logo'></span>" + data[i].long + " - " + data[i].short + "</td><td> $" + numFormat + "</td><td> $" + numFormat1 + "</td><td>" + numFormat2 + "</td><td class='marketChange'>" + data[i].cap24hrChange + "% </td></tr>");
                }
                $("<tbody/>", {
                    "class": "mainTable",
                    html: items.join("")
                }).insertAfter("#tableHeader");
            },
            complete: function() {
                $("#loading").addClass("hide");
                $('#dataTable').DataTable({
                    "lengthMenu": [ 20, 50, 75, 100 ],
                    "order": [[ 3, "desc" ]],
                    language: { search: "" }
                });
                $('#dataTable_filter input[type="search"]').attr('placeholder', 'Search for coins');
                $('#dataTable_filter input[type="search"]').css("padding-left","9px");
            }
        });
        setTimeout(executeQuery, 5000);
    }

    $(document).ready(function() {
        setTimeout(executeQuery, 5000);
    });
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

只创建一次数据表。将代码从完成移动到文档就绪。每次新的完成都不要创建tbody。他们将它们附加到主体上。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Crypto Market Cap</title>
    <link rel="icon" type="image/png" href="imgs/favicon.ico" />
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
    <link rel="stylesheet" type="text/css" href="css/spritesheet.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-112760236-1"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'UA-112760236-1');
    </script>
    <style>
        #tableHeader tr td { font-weight:bold }
    </style>
</head>
<body>
    <img src="imgs/spritesheet.png" width="0" height="0" style="display: none">
    <div class="container">
        <div class="row" style="text-align:center;margin-bottom:30px">
            <h2 class="col-xs-12">
                Cryptocurrency Market Capitalizations
            </h2>
            <h5>$USD</h5>
        </div>
        <div class="row">
            <div class="col-xs-12" style="padding:0">
                <table id="dataTable" class="table table-bordered hover" style="margin:0 auto">
                    <thead id="tableHeader">
                        <tr>
                            <td>#</td>
                            <td>Name</td>
                            <td>Price</td>
                            <td>Market Cap</td>
                            <td>Available Supply</td>
                            <td>24 HR % Change</td>
                        </tr>
                    </thead>
                    <tbody class="mainTable">
                    </tbody>
                </table>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12" style="text-align:center;margin-top:50px">
                <img src="imgs/loading.gif" style="height:120px" id="loading">
            </div>
        </div>
    </div>
<script>
    function executeQuery() {
        $.ajax({
            url: "http://coincap.io/front",
            type: "GET",
            dataType: "json",
            success: function (data) {
                var items = [];
                var len = data.length;
                for (var i = 0; i < len; i++) {
                    var numFormat = data[i].price.toLocaleString("en");
                    var numFormat1 = data[i].mktcap.toLocaleString("en");
                    var numFormat2 = data[i].supply.toLocaleString("en");
                    var lowerCaseName = data[i].long.toLowerCase();
                    items.push("<tr><td>" + [i+1] + "</td><td> <span class='sprite sprite-" + lowerCaseName + " small_coin_logo'></span>" + data[i].long + " - " + data[i].short + "</td><td> $" + numFormat + "</td><td> $" + numFormat1 + "</td><td>" + numFormat2 + "</td><td class='marketChange'>" + data[i].cap24hrChange + "% </td></tr>");
                }
                $(".mainTable").append(items.join(""));
            },
            complete: function() {

            }
        });
        setTimeout(executeQuery, 5000);
    }

    $(document).ready(function() { $("#loading").addClass("hide");
                $('#dataTable').DataTable({
                    "lengthMenu": [ 20, 50, 75, 100 ],
                    "order": [[ 3, "desc" ]],
                    language: { search: "" }
                });
                $('#dataTable_filter input[type="search"]').attr('placeholder', 'Search for coins');
                $('#dataTable_filter input[type="search"]').css("padding-left","9px");
        setTimeout(executeQuery, 5000);
    });
</script>
</body></html>