【问题标题】:Bootstrap 3 DataTable export to Excel not exporting table dataBootstrap 3 DataTable 导出到 Excel 不导出表数据
【发布时间】:2018-11-19 04:08:31
【问题描述】:

我正在尝试使用以下示例将表格的内容导出到 MS Excel:https://datatables.net/extensions/buttons/examples/styling/bootstrap.html

我在页面上正确显示了所有内容;但是,当我导出时,我只会得到标题和列标题。我在java中生成表格内容。

页面图片:

[![在此处输入图片描述][1]][1]

输出:

[![在此处输入图片描述][2]][2]

------------------------------------------ ------------------------------ 第二次尝试

我已经改变了我的方法,现在正在传递 json。但是,现在按钮没有显示,表格也没有格式化。控制台日志中没有错误。

------------------------------------------ ------------------------------ 第三次尝试

好的,我已经弄清楚了如何传递 JSON 并使用 AJAX 填充表格。但是,导出到 Excel 仍然只导出名称和表格标题。

------------------------------------------ ------------------------------ 第四次尝试

我正在尝试:

$('#joinedTable').DataTable( {
   "ajax": responseJson1a,
} );

我也试过了:

$('#joinedTable').DataTable( {
   "ajax": JSON.stringify(responseJson1a),
} );

我已经清理了库。

HTML:

<!DOCTYPE html>
<html>
    <head>
        <title>Group Summary</title>
        <meta http-equiv=Content-Type content="text/html; charset=utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="A Scout award tracking application">
        <meta name="author" content="Glyndwr (Wirrin) Bartlett">

        <!-- JQuery -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

        <!-- Validate -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js"></script>

        <!-- Bootstrap -->
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>

        <!-- Bootstrap Date Picker-->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>    
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.min.js"></script>

        <!-- DataTables -->
        <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>


        <!-- Le styles -->
        <!-- Bootstrap -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

        <!-- DataTables -->
        <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
        <link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.5.1/css/buttons.dataTables.min.css">
    </head>

  <body>

    <div id="groupSummary"  class="container-fluid" style="background-repeat: repeat; background-image: url('images/body-bg.jpg');">

        <div id="includedContent"></div>

        <form data-toggle="validator" role="form" id="showGroupSummaryForm">
            <div class="row">
                <div class="container-fluid">
                    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                        <div class="jumbotron">
                            <h3>Group Summary</h3>

                            <div class="container">

                                <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
                                    <div class="form-group">
                                        <div class="input-group date" id="datepicker1">
                                            <input type="text" id="startDate" class="form-control" placeholder="Start Date">
                                            <span class="input-group-addon">
                                                <span class="glyphicon glyphicon-calendar"></span>
                                            </span>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
                                    <div class="form-group">
                                        <div class='input-group date' id='datepicker2'>
                                            <input type='text' id="endDate" class="form-control" placeholder="End Date">
                                            <span class="input-group-addon">
                                                <span class="glyphicon glyphicon-calendar"></span>
                                            </span>
                                        </div>
                                    </div>
                                </div>

                                <button id='submit' class='btn btn-primary btn-lg'>Display Details</button>

                            </div>
                            <div class="container" id=joined>
                                <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
                                    <table id="joinedTable" class="display" style="width:100%">
                                        <thead>
                                            <tr>
                                              <th>section</th>
                                              <th>subSection</th>
                                              <th>metric</th>
                                              <th>metricTotal</th>
                                            </tr>
                                        </thead>
                                    </table>
                                    <div style="text-align: center;">
                                        <span id="ajaxGetUserServletResponse1" style="color: red;"></span>
                                    </div>
                                </div>
                            </div><!-- /container -->

                        </div>
                    </div>
                </div>
            </div><!-- /row -->
        </form>

    </div> <!-- /container -->



    <!-- Le javascript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.flash.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/vfs_fonts.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.print.min.js"></script>

    <script src="js/groupSummary-ajax.js"></script>

  </body>
</html>

阿贾克斯:

$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip(); 

//  $('#joinedTable').DataTable( {
//      "paging":   false,
//        "ordering": false,
//        "info":     false,
//        "searching": false,
//        dom: 'Bfrtip',
//        buttons: ['copy', 'csv', 'excel', 'pdf', 'print'],
//    } );



    $("#showGroupSummaryForm").validate({
        //debug: true,

        rules: {
            startDate: {
                required: true
            },

            endDate: {
                required: true
            }
        },

        messages: {
            startDate: {
                required: "Please select a start date."
            },

            endDate: {
                required: "Please select an end date."
            }
        },

        submitHandler : function(showGroupSummaryForm) {

            $('#joinedTable tbody > tr').remove();
            $('#ajaxGetUserServletResponse1').text('');

            var dataToBeSent  = {
                    ssAccountID : sessionStorage.getItem('ssAccountID'),
                    startDate : $("#startDate").val(),
                    endDate: $("#endDate").val()
            };

            //Joined
            $.ajax({
                url : 'GroupSummaryJoinedView', // Your Servlet mapping or JSP(not suggested)
                data : dataToBeSent, 
                type : 'POST',  
            })
            .fail (function(jqXHR, textStatus, errorThrown) {
                //alert(jqXHR.responseText);
                if(jqXHR.responseText.includes('No members joined in this date range')){
                    $('#ajaxGetUserServletResponse1').text('No members joined in this date range.');
                }else{
                    $('#ajaxGetUserServletResponse1').text('Error getting joined data.');

                }
                $("#datepicker1").focus();
            })
            .done(function(responseJson1a){
                dataType: "json";
//              alert(JSON.stringify(responseJson1a)); 
//              Result of alert is:
//                  [{"section":"Cub","subSection":"Explorer","metric":"Joined","metricTotal":5},{"section":"Cub","subSection":"Pioneer","metric":"Joined","metricTotal":8},{"section":"Joey","subSection":"blank","metric":"Joined","metricTotal":1},{"section":"Leader","subSection":"blank","metric":"Joined","metricTotal":5},{"section":"Rover","subSection":"blank","metric":"Joined","metricTotal":1},{"section":"Scout","subSection":"blank","metric":"Joined","metricTotal":2}]
                $('#joinedTable').DataTable( {
                    "ajax": responseJson1a,
                } );

            })
        }
    })

}); // end document.ready

$(function(){
    $("#includedContent").load("Menu.html");

    $('#datepicker1').datepicker({
        format: 'dd/mm/yyyy',
            });
    $('#datepicker2').datepicker({
        useCurrent: false, //Important! See issue #1075
        format: 'dd/mm/yyyy',
    });
    $("#datepicker1").on("dp.change", function (e) {
        $('#datepicker2').data("DatePicker").minDate(e.date);
    });
    $("#datepicker2").on("dp.change", function (e) {
        $('#datepicker1').data("DatePicker").maxDate(e.date);
    });
});

这在控制台中给我一个错误:

Uncaught TypeError: $(...).DataTable is not a function
    at Object.<anonymous> (groupSummary-ajax.js:70)
    at i (eval at globalEval (jquery-2.2.4.min.js:2), <anonymous>:2:27449)
    at Object.fireWith [as resolveWith] (eval at globalEval (jquery-2.2.4.min.js:2), <anonymous>:2:28213)
    at y (eval at globalEval (jquery-2.2.4.min.js:2), <anonymous>:4:22721)
    at XMLHttpRequest.c (eval at globalEval (jquery-2.2.4.min.js:2), <anonymous>:4:26925)

------------------------------------------ ------------------------------ 缩小错误范围

该错误不是由于 HTML 表是从 JSON 填充的。 “$('#joinedTable').DataTable();”在“.done(function(responseJson1a)”中会导致错误。下面的工作直到“$('#joinedTable').DataTable();”被取消注释。但是,只有

<tr>
   <td>Cubs</td>
   <td>3</td>
</tr>
<tr>
   <td>Scouts</td>
   <td>5</td>
</tr>

已导出。不是

<tr>
   <td>Cubs</td>
   <td>9</td>
</tr>
<tr>
   <td>Scouts</td>
   <td>10</td>
</tr>

HTML:

<!DOCTYPE html>
<html>
    <head>
        <title>Group Summary</title>
        <meta http-equiv=Content-Type content="text/html; charset=utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="A Scout award tracking application">
        <meta name="author" content="Glyndwr (Wirrin) Bartlett">

        <!-- JQuery -->
        <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

        <!-- Validate -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js"></script>

        <!-- Bootstrap -->
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>

        <!-- Bootstrap Date Picker-->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>    
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.min.js"></script>

        <!-- DataTables -->
        <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>


        <!-- Le styles -->
        <!-- Bootstrap -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

        <!-- DataTables -->
        <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
        <link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.5.1/css/buttons.dataTables.min.css">
    </head>

  <body>

    <div id="groupSummary"  class="container-fluid" style="background-repeat: repeat; background-image: url('images/body-bg.jpg');">

        <div id="includedContent"></div>

        <form data-toggle="validator" role="form" id="showGroupSummaryForm">
            <div class="row">
                <div class="container-fluid">
                    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                        <div class="jumbotron">
                            <h3>Group Summary</h3>

                            <div class="container">

                                <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
                                    <div class="form-group">
                                        <div class="input-group date" id="datepicker1">
                                            <input type="text" id="startDate" class="form-control" placeholder="Start Date">
                                            <span class="input-group-addon">
                                                <span class="glyphicon glyphicon-calendar"></span>
                                            </span>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
                                    <div class="form-group">
                                        <div class='input-group date' id='datepicker2'>
                                            <input type='text' id="endDate" class="form-control" placeholder="End Date">
                                            <span class="input-group-addon">
                                                <span class="glyphicon glyphicon-calendar"></span>
                                            </span>
                                        </div>
                                    </div>
                                </div>

                                <button id='submit' class='btn btn-primary btn-lg'>Display Details</button>

                            </div>
                            <div class="container" id=joined>
                                <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
                                    <table class="table table-hover table-bordered" id="joinedTable">
                                        <thead>
                                            <tr>
                                              <th>Section</th>
                                              <th>Joined</th>
                                            </tr>
                                        </thead>
                                            <tbody id="mytablebody">
                                                <tr>
                                                    <td>Cubs</td>
                                                    <td>3</td>
                                                  </tr>
                                                  <tr>
                                                    <td>Scouts</td>
                                                    <td>5</td>
                                                  </tr>
                                             </tbody>
                                        <!--<tbody id="mytablebody"></tbody> -->
                                    </table>
                                    <div style="text-align: center;">
                                        <span id="ajaxGetUserServletResponse1" style="color: red;"></span>
                                    </div>
                                </div>
                            </div><!-- /container -->

                        </div>
                    </div>
                </div>
            </div><!-- /row -->
        </form>

    </div> <!-- /container -->



    <!-- Le javascript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.flash.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/vfs_fonts.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.print.min.js"></script>

    <script src="js/DataTable.js"></script>

  </body>
</html>

AJAX:

$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip(); 

    $('#joinedTable').DataTable( {
        "paging":   false,
        "ordering": false,
        "info":     false,
        "searching": false,
        dom: 'Bfrtip',
        buttons: ['copy', 'csv', 'excel', 'pdf', 'print'],
    } );



    $("#showGroupSummaryForm").validate({
        //debug: true,

        rules: {
            startDate: {
                required: true
            },

            endDate: {
                required: true
            }
        },

        messages: {
            startDate: {
                required: "Please select a start date."
            },

            endDate: {
                required: "Please select an end date."
            }
        },

        submitHandler : function(showGroupSummaryForm) {

            $('#joinedTable tbody > tr').remove();
            $('#ajaxGetUserServletResponse1').text('');

            var dataToBeSent  = {
                    ssAccountID : sessionStorage.getItem('ssAccountID'),
                    startDate : $("#startDate").val(),
                    endDate: $("#endDate").val()
            };

            //Joined
            $.ajax({
                url : 'GroupSummaryJoinedView', // Your Servlet mapping or JSP(not suggested)
                data : dataToBeSent, 
                type : 'POST',  
            })
            .fail (function(jqXHR, textStatus, errorThrown) {
                //alert(jqXHR.responseText);
                if(jqXHR.responseText.includes('No members joined in this date range')){
                    $('#ajaxGetUserServletResponse1').text('No members joined in this date range.');
                }else{
                    $('#ajaxGetUserServletResponse1').text('Error getting joined data.');

                }
                $("#datepicker1").focus();
            })
            .done(function(responseJson1a){
                dataType: "json";

//              alert(JSON.stringify(responseJson1a)); 
//              Result of alert is:
//                  [{"section":"Cub","subSection":"Explorer","metric":"Joined","metricTotal":5},{"section":"Cub","subSection":"Pioneer","metric":"Joined","metricTotal":8},{"section":"Joey","subSection":"blank","metric":"Joined","metricTotal":1},{"section":"Leader","subSection":"blank","metric":"Joined","metricTotal":5},{"section":"Rover","subSection":"blank","metric":"Joined","metricTotal":1},{"section":"Scout","subSection":"blank","metric":"Joined","metricTotal":2}]

                 var tablebody2 = '          <tr>' + 
                    '<td>Cubs</td>' +
                    '<td>9</td>' +
                  '</tr>' +
                  '<tr>' +
                    '<td>Scouts</td>' +
                    '<td>10</td>' +
                  '</tr>';

                 $("#mytablebody").empty();
                 $("#mytablebody").append(tablebody2);
//               $('#joinedTable').DataTable(); // Uncomment this and the error happens
            })
        }
    })

}); // end document.ready

$(function(){
    $("#includedContent").load("Menu.html");

    $('#datepicker1').datepicker({
        format: 'dd/mm/yyyy',
            });
    $('#datepicker2').datepicker({
        useCurrent: false, //Important! See issue #1075
        format: 'dd/mm/yyyy',
    });
    $("#datepicker1").on("dp.change", function (e) {
        $('#datepicker2').data("DatePicker").minDate(e.date);
    });
    $("#datepicker2").on("dp.change", function (e) {
        $('#datepicker1').data("DatePicker").maxDate(e.date);
    });
});

【问题讨论】:

    标签: java html ajax twitter-bootstrap


    【解决方案1】:

    您在表格被填充之前初始化dataTable,这就是为什么它看不到您通过ajax 获取的任何动态数据。把数据表渲染好后的初始化代码(见下文-- INIT --

    $(document).ready(function(){
        $('[data-toggle="tooltip"]').tooltip();
    
        // push the init code 
    
        $("#showGroupSummaryForm").validate({
            //debug: true,
    
            rules: {
                startDate: {
                    required: true
                },
    
                endDate: {
                    required: true
                }
            },
    
            messages: {
                startDate: {
                    required: "Please select a start date."
                },
    
                endDate: {
                    required: "Please select an end date."
                }
            },
    
            submitHandler : function(showGroupSummaryForm) {
    
                $('#joinedTable tbody > tr').remove();
                $('#ajaxGetUserServletResponse1').text('');
    
                var dataToBeSent  = {
                        ssAccountID : sessionStorage.getItem('ssAccountID'),
                        startDate : $("#startDate").val(),
                        endDate: $("#endDate").val()
                };
    
                //Joined
                $.ajax({
                    url : 'GroupSummaryJoinedView', // Your Servlet mapping or JSP(not suggested)
                    data : dataToBeSent, 
                    type : 'POST',
                    dataType: 'JSON',
                })
                .fail (function(jqXHR, textStatus, errorThrown) {
                    if(jqXHR.responseText.includes('No members joined in this date range')){
                        $('#ajaxGetUserServletResponse1').text('No members joined in this date range.');
                    }else{
                        $('#ajaxGetUserServletResponse1').text('Error getting joined data.');
    
                    }
                    $("#datepicker1").focus();
                })
                .done(function(responseJson1a){
                    // JSON response to populate the joined table
                    populateTable(responseJson1a)
    
                    // -- INIT -- 
                    // initialize the table
                    // after the data has loaded
                    $('#joinedTable').DataTable( {
                        dom: 'Bfrtip',
                        buttons: ['copy', 'csv', 'excel', 'pdf', 'print'],
                        serverSide: true,
                        initComplete : function () {
                        table.buttons().container()
                           .appendTo( $('#joinedSpace .col-sm-6:eq(0)'));
                        },
                    });
                })
            }
        });
    }); // end document.ready
    
    function populateTable(object) {
    
        var obj = object;
        var table = $("<table id='joinedTable'/>");
        table[0].border = "1";
        var columns = Object.keys(obj[0]);
        var columnCount = columns.length;
        var row = $(table[0].insertRow(-1));
        for (var i = 0; i < columnCount; i++) {
            var headerCell = $("<th />");
            headerCell.html([columns[i]]);
            row.append(headerCell);
        }
    
        for (var i = 0; i < obj.length; i++) {
            row = $(table[0].insertRow(-1));
            for (var j = 0; j < columnCount; j++) {
                var cell = $("<td />");
                cell.html(obj[i][columns[j]]);
                row.append(cell);
            }
        }
    
        var dvTable = $("#joinedSpace");
    //    dvTable.html("");
        dvTable.append(table);
    }
    
    $(function(){
        $("#includedContent").load("MenuGL.html");
    
        $('#datepicker1').datepicker({
            format: 'dd/mm/yyyy',
                });
        $('#datepicker2').datepicker({
            useCurrent: false, //Important! See issue #1075
            format: 'dd/mm/yyyy',
        });
        $("#datepicker1").on("dp.change", function (e) {
            $('#datepicker2').data("DatePicker").minDate(e.date);
        });
        $("#datepicker2").on("dp.change", function (e) {
            $('#datepicker1').data("DatePicker").maxDate(e.date);
        });
    });
    

    另一种避免您自己填充表格的方法是将url 直接传递给dataTable 插件并让表格处理ajax 和数据填充。控制器必须以here指定的格式返回数据

        $('#example').DataTable( {
            "ajax": 'pathToYourController',
            dom: 'Bfrtip',
            buttons: [
                'copy', 'csv', 'excel', 'pdf', 'print'
            ]
        } );
    

    【讨论】:

    • 非常感谢您的回复;不胜感激。不幸的是,这不起作用 - 没有改变当前的行动。我将 jQuery 放在 DataTable 之后。我尝试了“更改”和“按键粘贴”。请不要说我已经更新了图像,因为“导出”按钮什么都不做,可能是一个红鲱鱼。我已经查看了 Column Renderer,发现它很难理解。我不是程序员,我为我的组织免费做这件事。我是正确创建表格还是应该以不同的方式完成?猴子看,猴子做的例子将不胜感激。
    • @Glyn 在应用程序上做得很好!继续努力吧。我已经更新了我的答案以添加一些调试步骤,尝试这些步骤,希望你会看到文本发生变化。我不知道为什么导出按钮不起作用,但它可能表明 javascript 在某处中断,在浏览器上打开你的 javascript 控制台,它应该会告诉你发生的所有错误,如果你使用的是 chrome,你可以关注this tutorial
    • 感谢您的鼓励。我有人教我如何使用控制台,所以我现在虔诚地使用它。当他们向我展示时,我发现了大量我能够修复的错误。现在没有错误。我认为我做这一切都是错误的,并且正在调查使用 JSON 而不是 HTML 从数据库的 java 读取中返回值,然后使用 javascript 来构建表。你会这样做吗?
    • @Glyn 以 JSON 格式传递数据并让表格处理它,让您免于编写 html。那并让 dataTable 处理输入字段可能是一种更清洁的方法。我会尝试以这种心态编造一些东西,我会更新我的答案。
    • 我已经弄清楚如何从 JSON 构建每个表数据行;但是,导出到 Excel 中仍然没有提取数据(只是名称和列标题)。
    【解决方案2】:

    解析要点有:

    var table = $('#joinedTable').DataTable( {
    
    table.clear();
    table.rows.add(responseJson1a).draw();
    

    HTML:

    <!DOCTYPE html>
    <html>
        <head>
            <title>Group Summary</title>
            <meta http-equiv=Content-Type content="text/html; charset=utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <meta name="description" content="A Scout award tracking application">
            <meta name="author" content="Glyndwr (Wirrin) Bartlett">
    
            <!-- JQuery -->
            <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
            <!-- Validate -->
            <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js"></script>
    
            <!-- Bootstrap -->
            <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
    
            <!-- Bootstrap Date Picker-->
            <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>    
            <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.min.js"></script>
    
            <!-- DataTables -->
            <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
    
    
            <!-- Le styles -->
            <!-- Bootstrap -->
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    
            <!-- DataTables -->
            <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
            <link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.5.1/css/buttons.dataTables.min.css">
        </head>
    
      <body>
    
        <div id="groupSummary"  class="container-fluid" style="background-repeat: repeat; background-image: url('images/body-bg.jpg');">
    
            <div id="includedContent"></div>
    
            <form data-toggle="validator" role="form" id="showGroupSummaryForm">
                <div class="row">
                    <div class="container-fluid">
                        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                            <div class="jumbotron">
                                <h3>Group Summary</h3>
    
                                <div class="container">
    
                                    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
                                        <div class="form-group">
                                            <div class="input-group date" id="datepicker1">
                                                <input type="text" id="startDate" class="form-control" placeholder="Start Date">
                                                <span class="input-group-addon">
                                                    <span class="glyphicon glyphicon-calendar"></span>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
    
                                    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
                                        <div class="form-group">
                                            <div class='input-group date' id='datepicker2'>
                                                <input type='text' id="endDate" class="form-control" placeholder="End Date">
                                                <span class="input-group-addon">
                                                    <span class="glyphicon glyphicon-calendar"></span>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
    
                                    <button id='submit' class='btn btn-primary btn-lg'>Display Details</button>
    
                                </div>
                                <div class="container" id=joined>
                                    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
                                        <table class="table table-hover table-bordered" id="joinedTable">
                                            <thead>
                                                <tr>
                                                  <th>Section</th>
                                                  <th>Joined</th>
                                                </tr>
                                            </thead>
                                            <tbody id="mytablebody">
                                            </tbody>
                                        </table>
                                        <div style="text-align: center;">
                                            <span id="ajaxGetUserServletResponse1" style="color: red;"></span>
                                        </div>
                                    </div>
                                </div><!-- /container -->
    
                            </div>
                        </div>
                    </div>
                </div><!-- /row -->
            </form>
    
        </div> <!-- /container -->
    
    
    
        <!-- Le javascript
        ================================================== -->
        <!-- Placed at the end of the document so the pages load faster -->
        <script src="https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js"></script>
        <script src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.flash.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/pdfmake.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/vfs_fonts.js"></script>
        <script src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.html5.min.js"></script>
        <script src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.print.min.js"></script>
    
        <script src="js/DataTable.js"></script>
    
      </body>
    </html>
    

    AJAX:

    $(document).ready(function(){
        $('[data-toggle="tooltip"]').tooltip(); 
    
        var table = $('#joinedTable').DataTable( {
            "paging":   false,
            "ordering": false,
            "info":     false,
            "searching": false,
            dom: 'Bfrtip',
            buttons: ['copy', 'csv', 'excel', 'pdf', 'print'],
            columns: [
                      {data: 'section'},
                      {data: 'metricTotal'}
                      ]
        } );
    
    
    
        $("#showGroupSummaryForm").validate({
            //debug: true,
    
            rules: {
                startDate: {
                    required: true
                },
    
                endDate: {
                    required: true
                }
            },
    
            messages: {
                startDate: {
                    required: "Please select a start date."
                },
    
                endDate: {
                    required: "Please select an end date."
                }
            },
    
            submitHandler : function(showGroupSummaryForm) {
    
                $('#ajaxGetUserServletResponse1').text('');
    
                var dataToBeSent  = {
                        ssAccountID : sessionStorage.getItem('ssAccountID'),
                        startDate : $("#startDate").val(),
                        endDate: $("#endDate").val()
                };
    
                //Joined
                $.ajax({
                    url : 'GroupSummaryJoinedView', // Your Servlet mapping or JSP(not suggested)
                    data : dataToBeSent, 
                    type : 'POST',  
                })
                .fail (function(jqXHR, textStatus, errorThrown) {
                    //alert(jqXHR.responseText);
                    if(jqXHR.responseText.includes('No members joined in this date range')){
                        $('#ajaxGetUserServletResponse1').text('No members joined in this date range.');
                    }else{
                        $('#ajaxGetUserServletResponse1').text('Error getting joined data.');
    
                    }
                    $("#startDate").focus();
                })
                .done(function(responseJson1a){
                    dataType: "json";
    
    //              alert(JSON.stringify(responseJson1a)); 
    //              Result of alert is:
    //                  [{"section":"Cub","subSection":"Explorer","metric":"Joined","metricTotal":5},{"section":"Cub","subSection":"Pioneer","metric":"Joined","metricTotal":8},{"section":"Joey","subSection":"blank","metric":"Joined","metricTotal":1},{"section":"Leader","subSection":"blank","metric":"Joined","metricTotal":5},{"section":"Rover","subSection":"blank","metric":"Joined","metricTotal":1},{"section":"Scout","subSection":"blank","metric":"Joined","metricTotal":2}]
    
                     table.clear();
                     table.rows.add(responseJson1a).draw();
                })
            }
        })
    
    }); // end document.ready
    
    $(function(){
        $("#includedContent").load("Menu.html");
    
        $('#datepicker1').datepicker({
            format: 'dd/mm/yyyy',
                });
        $('#datepicker2').datepicker({
            useCurrent: false, //Important! See issue #1075
            format: 'dd/mm/yyyy',
        });
        $("#datepicker1").on("dp.change", function (e) {
            $('#datepicker2').data("DatePicker").minDate(e.date);
        });
        $("#datepicker2").on("dp.change", function (e) {
            $('#datepicker1').data("DatePicker").maxDate(e.date);
        });
    });
    

    【讨论】:

    • 太棒了!我很高兴你让它工作。我完全忘记了使用add()
    猜你喜欢
    • 2012-08-01
    • 2016-04-16
    • 2019-05-13
    • 1970-01-01
    • 2017-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多