【问题标题】:Display dynamic table values using dataTables使用 dataTables 显示动态表值
【发布时间】:2017-06-15 07:36:29
【问题描述】:

我在使用 dataTables 显示数据库中的值时遇到问题。 我无法触发 $('#id').DataTable() 将我的 html 表魔术到 dataTables 中,而简单明了的 html 可以正确显示它。我认为我的问题出在 ajax 中。所以这是我的代码:

任何帮助将不胜感激! :))

<script type="text/javascript" src="{!! asset('js/jquery.datatables.min.js') !!}"></script> 
<script type="text/javascript" src="{!! asset('js/jquery-3.2.1.min.js') !!}"></script> 
<script type="text/javascript">
        $(function(){

            $(".list-link").click(function(e) {  //for my
                e.stopPropagation();             //siderbar accordion
                                                 //animation
            });                                     

            $("#schooltableDesc").DataTable();

            $("#generateBtn").on("click", function() {  //onClick, the ajax tables
                $("#schooltableDesc").empty();          //will be empty and will redraw
                $("#schooltableAsc").empty();           //with new values based on the dropdown
                $("#collegetableDesc").empty();         
                $("#collegetableAsc").empty();
                $("#programtableDesc").empty();
                $("#programtableAsc").empty(); 


            var yearData = {
                from: $('#datefrom').val(),
                to: $('#dateto').val(),

            }; 

                $.ajax({
                url: '/university-analysis/where-between',
                data: yearData,
                dataType: 'json',
                method: 'get',
                success: function (response) {   

                    // $("#totals").html(response.h); 
                    $("#schooltableDesc").html(response.fsD);                     
                    $("#collegetableDesc").html(response.cD);
                    $("#programtableDesc").html(response.pD); 
                    $("#schooltableAsc").html(response.fsA);             
                    $("#collegetableAsc").html(response.cA);
                    $("#programtableAsc").html(response.pA); 

                    $("#popu").text(response.total_enrolled);
                     $("#males").text(response.total_males); 
                     $("#females").text(response.total_females);             
                     $("#no_of_schools").text(response.schools);
                     $("#ave_age").text(response.avg_a);  



                }
            }); 

这是表格的html

<table class="table table-bordered" id="schooltableDesc">
      <thead>
             <th>Age</th>
             <th>Top 5 Feeder Schools</th>
             <th>Male</th>
             <th>Female</th>
             <th>Total</th>
             <th>Average rate</th>
     </thead>

     <tbody>
            @foreach($schoolsD as $t)
                @php
                $age = $t->AverageAge;
                $fs = $t->HS_School;
                $bp = $t->Male;
                $gp = $t->Female;
                $total = $t->TOTAL;
                $avg = $t->arate; 
                @endphp
                <tr>
                    <td>{{$age}}</td>
                    <td>{{ucwords(strtolower($fs))}}</td>
                    <td>{{$bp}}</td>
                    <td>{{$gp}}</td>
                    <td>{{$total}}</td>
                    <td>{{number_format($avg, 3)}}%</td>                    
                </tr>
                @endforeach

    </tbody>
    </table>

然后是ajax的控制器:

    //desc
    $schoolsD = DB::table("vw_es_students")
        ->selectRaw("AVG(DATEDIFF(year, [DateOfBirth], GETDATE())) AS \"AverageAge\", HS_School, SUM(IIF(Gender = 'M', 1, 0)) AS \"Male\", SUM(IIF(Gender = 'F', 1, 0)) AS \"Female\", count(*) as \"TOTAL\"")
        ->whereRaw(sprintf("DateAdmitted BETWEEN '%s-01-01' AND ('%s-12-31') and HS_School != ''", $yearFrom, $yearTo))
        ->whereRaw("HS_School != ''")
        ->groupBy("HS_School")->orderBy("TOTAL", "desc")->get(); 




$responseSchoolsD = "<table class='table no-border' id='schooltableDesc'>
                         <thead>
                         <th>Age</th>
                         <th>Top 5 Feeder Schools</th>
                         <th>Male</th>
                         <th>Female</th>
                         <th>Total</th>
                         </thead><tbody>";


         foreach($schoolsD as $t){

                 $age = $t->AverageAge;
                 $fs = $t->HS_School;
                 $bp = $t->Male;
                 $gp = $t->Female;
                 $total = $t->TOTAL;


            $responseSchoolsD .=  "<tr>";

            $responseSchoolsD .= "<td>" . $age . "</td>";
            $responseSchoolsD .= "<td>" . $fs . "</td>";            
            $responseSchoolsD .= "<td>" . $bp . "</td>";     
            $responseSchoolsD .= "<td>" . $gp . "</td>";
            $responseSchoolsD .= "<td>" . $total . "</td>";

        } 

         $responseSchoolsD .= "</tr></table>"; 

【问题讨论】:

  • 你需要在成功回调中使用$("#schooltableDesc").DataTable().fnDraw();我猜的行更改后重绘它!
  • 这样的,先生? success: function (response) { $("#schooltableDesc").DataTable().html(response.fsD);

标签: javascript php jquery ajax datatables


【解决方案1】:

您可以尝试获取项目,然后像这样填充表格:

   <script type="text/javascript">
        (function ($) {
        $(document).ready(function () {
        itemsTable = null,
        getItems = function () {
                            return $.Deferred(function () {
                                var that = this;
                                $.getJSON('/university-analysis/where-between', function (data) {
                                    that.resolve(data);
                                });
                            });
                        },

            $(".list-link").click(function(e) {  //for my
                e.stopPropagation();             //siderbar accordion
                                                 //animation
            });                                     

            $("#schooltableDesc").DataTable();

            $("#generateBtn").on("click", function() {  //onClick, the ajax tables
                $("#schooltableDesc").empty();          //will be empty and will redraw
                $("#schooltableAsc").empty();           //with new values based on the dropdown
                $("#collegetableDesc").empty();         
                $("#collegetableAsc").empty();
                $("#programtableDesc").empty();
                $("#programtableAsc").empty(); 
            });

            var yearData = {
                from: $('#datefrom').val(),
                to: $('#dateto').val(),

            }; 

            showItemsTable = function () {
                        return $.Deferred(function () {
                            var that = this;
                            getItems().done(function (itemsData) {
                                try {
                                   itemsTable = $("#schooltableDesc").DataTable({

                                        data: itemsData,
                                         columns: [
                                        DataTables.expandCol,
                                        {"data": 'age'},
                                        {"data": 'your data...'},
                                        {"data": 'your data...'},
                                        {"data": '...'},
                                        {"data": '...'},
                                        {"data": '...'},
                                        {"data": '...'}
                                    ]
                                    });
                                    // $("#totals").html(response.h); 
                                    $("#schooltableDesc").html(response.fsD);                     
                                    $("#collegetableDesc").html(response.cD);
                                    $("#programtableDesc").html(response.pD); 
                                    $("#schooltableAsc").html(response.fsA);             
                                    $("#collegetableAsc").html(response.cA);
                                    $("#programtableAsc").html(response.pA); 

                                    $("#popu").text(response.total_enrolled);
                                     $("#males").text(response.total_males); 
                                     $("#females").text(response.total_females);             
                                     $("#no_of_schools").text(response.schools);
                                     $("#ave_age").text(response.avg_a); 
                                    //console.log(itemsTable);

                                    that.resolve();
                                }catch (e) {
                                    console.log(e.message);
                                }
                            });
                        });
                    },
            showItemsTable();



             });//end of doc ready
       });</script>

希望对你有帮助

【讨论】:

  • 感谢先生的回复!我会先尝试理解您的代码,因为这种方法对我来说看起来很复杂 XD
  • 我编辑了我的答案,以便您更容易看到我的代码是如何工作的
【解决方案2】:

问题是您必须调用创建 DataTable 的代码行

 $("#schooltableDesc").DataTable();

之后发出一个成功返回并填充您的 html 表的 http 请求。

在您的示例中,DataTable 甚至在任何数据存在之前就已创建

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 2015-01-24
    • 1970-01-01
    相关资源
    最近更新 更多