【问题标题】:Datatable not working on ajax call数据表不适用于ajax调用
【发布时间】:2018-02-28 05:45:54
【问题描述】:

我在我的 Web 应用程序中使用 Datatable。 以下是我使用 ajax 获取数据的简单代码。

<script>
    $(document).ready(function() {
        $('#mytable').DataTable();
    } );
</script>

<body>
  <h2>AJAX SELECT</h2><hr>
  <div align="center">
    Select Team :
    <select name="select" id ='teamSelect'>
        <option value="">Select Value</option>
        <option value="op2">Company 1</option>
    </select>
  </div>
  <div id='tableContainer' align="center"></div>

 <script>
    $(function() {
        $("#teamSelect").bind("change", function() {
            $.ajax({
                type: "GET", 
                url: "getData.php",
                "dataSrc": "tableData",
                success: function(html) {
                    $("#tableContainer").html(html);
                }
            });
        });

    });
</script>

和Getdata.php代码

<table id="mytable" class="display" cellspacing="0" width="50%">
    <thead>
    <tr>
        <th>First name</th>
        <th>Last Name</th>
        <th>Email</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>Airi Satou</td>
        <td>Accountant</td>
        <td>Tokyo</td>
    </tr>
    <tr>
        <td>Brielle Williamson</td>
        <td>Integration Specialist</td>
        <td>New York</td>
    </tr>
    <tr>
        <td>Herrod Chandler</td>
        <td>Sales Assistant</td>
        <td>San Francisco</td>
    </tr>
    <tr>
        <td>Rhona Davidson</td>
        <td>Integration Specialist</td>
        <td>Tokyo</td>
    </tr>
</tbody>

我将 Jquery、datatable css 和 js 都链接了。但它仍然以普通 HTML 表的形式返回输出。 没有发现控制台错误。 我需要数据表中的数据。那我怎样才能得到它。

我还在 index.php 页面中测试了数据表。它工作得很好。

【问题讨论】:

  • 您的问题与this有些相关。

标签: php jquery ajax datatable datatables


【解决方案1】:

您在添加表之前初始化数据表。你需要在ajax中初始化它

删除以下脚本

<script>
    $(document).ready(function() {
        $('#mytable').DataTable();
    } );
</script>

更新 ajax 如下:

<script>
    $(function() {
        $("#teamSelect").bind("change", function() {
            $.ajax({
                type: "GET", 
                url: "getData.php",
                "dataSrc": "tableData",
                success: function(html) {
                    $("#tableContainer").html(html);
                    $('#mytable').DataTable({ 
                      "destroy": true, //use for reinitialize datatable
                   });
                }
            });
        });

    });
</script>

【讨论】:

  • 它工作正常。但是你在 $('#mytable').DataTable(({
【解决方案2】:

<script>
$(document).ready(function() {
    $('#mytable').DataTable();
} );
</script>

Getdata.php 文件的底部还链接到数据表 css 和 js。

或者使用ajaxComplete function()来调用数据表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 2014-10-23
    • 2011-04-04
    • 2021-08-13
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多