使用dataTables显示动态表值

时间:2017-06-15 07:36:29

标签: javascript php jquery ajax datatables

我在使用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>"; 

2 个答案:

答案 0 :(得分:0)

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

   <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>

希望这有帮助

答案 1 :(得分:0)

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

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

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

在您的示例中,在没有任何数据存在之前就已经创建了DataTable

相关问题