使用多表

时间:2016-08-25 14:56:50

标签: php jquery json ajax datatables

在我的项目中,我使用DataTables显示我的数据,该数据是从PHP echo json_encode检索的。 PHP页面是一个返回JSON的脚本:

  {
    "sig1_re": [
      {
        "Ticket_RT": 716771,
        "Cable_de_renvoi": 45,
        "Longueur_de_ligne_(Selt)": 50,
        "Res_LigneCoupee": "short",
        "Ticket_fils": 152321,
        "Numero_ND": "",
        "Gamot_DateFermeture": "",
        "Difference_de_date": "",
        "Supprimer": "<a class='delete'><button>Delete</button></a>"
      },
      {
        "Ticket_RT": 716760,
        "Cable_de_renvoi": 45,
        "Longueur_de_ligne_(Selt)": 67,
        "Res_LigneCoupee": "open",
        "Ticket_fils": "",
        "Numero_ND": "",
        "Gamot_DateFermeture": "",
        "Difference_de_date": "",
        "Supprimer": "<a class='delete'><button>Delete</button></a>"
      }
    ],
    "bad_nd": [
      {
        "Ticket_RT": 716620,
        "Numero_ND": 236598741,
        "Supprimer": "<a class='delete'><button>Delete</button></a>"
      },
      {
        "Ticket_RT": 716577,
        "Numero_ND": 565231583,
        "Supprimer": "<a class='delete'><button>Delete</button></a>"
      }
    ]
  }

在我的第一次尝试中,我的HTLM中的每个表都有一个JS文件,效果很好,但我重复了相同的代码并且每次调用JSON echo,所以我决定将所有代码重新组合在一个JS中文件。

我设法导出了几乎所有的表选项,但是我在定义一些变量时遇到了麻烦;一个是hideFromExport:当我点击&#34; COPY&#34;时,我只需要复制第一列中的值。按钮。第二个问题是使用oTable来删除行。我想将这两个变量设置为与我的所有表兼容。 (在我下面的例子中我只使用了两个表,但在实际项目中我有更多)。

直播示例:http://live.datatables.net/peceqofo/1/edit

代码:

<!DOCTYPE html>
<html>
  <head>

<link href="https://raw.githubusercontent.com/twbs/bootstrap/master/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />    
<link href="https://cdn.datatables.net/responsive/2.1.0/css/responsive.dataTables.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/buttons/1.2.2/css/buttons.dataTables.css" rel="stylesheet" type="text/css" />
<link href="https://raw.githubusercontent.com/FortAwesome/Font-Awesome/master/css/font-awesome.min.css" rel="stylesheet" type="text/css" />            
    <meta charset=utf-8 />
    <title>DataTables - JS Bin</title>
  </head>
  <body>
    <div class="container" style="width: 90%;">
      <div class="panel panel-danger" style="margin: 5px;">
          <div class="panel-heading">
            <h2 class="panel-title">
              <b>My Test</b>
            </h2>
          </div>
          <div class="panel-body">
            <div class="table-responsive">
              <table id="tableA" class="table table-striped table-hover dt-responsive display nowrap" cellspacing="0" width="100%">
                  <thead>
                      <tr>
                          <th>Ticket_RT</th>
                          <th>Cable_de_renvoi</th>
                          <th>Longueur_de_ligne_</th>
                          <th>Res_LigneCoupee</th>   
                          <th>Ticket_fils RT</th>
                          <th>Gamot_DateFermeture</th>
                          <th>Numero_ND</th>
                          <th>Gamot_DateFermeture</th>    
                          <th>Supprimer</th>    
                      </tr>
                  </thead>
                  <tbody>
                  </tbody>
              </table>    
              <br />
              <table id="tableB" class="table table-striped table-hover dt-responsive display nowrap" cellspacing="0" width="100%">
                  <thead>
                      <tr>
                          <th>Ticket_RT</th>
                          <th>Numero_ND</th>
                          <th>Supprimer</th>
                      </tr>
                  </thead>
                  <tbody>
                  </tbody>
              </table>    
            </div>
          </div>
      </div>
    </div>

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.1.0/js/dataTables.responsive.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/dataTables.buttons.js"></script>
<script src="https://raw.githubusercontent.com/Stuk/jszip/master/dist/jszip.min.js"></script>
<script src="https://raw.githubusercontent.com/bpampuch/pdfmake/master/build/pdfmake.min.js"></script>
<script src="https://raw.githubusercontent.com/bpampuch/pdfmake/master/build/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.12/dataRender/ellipsis.js"></script>

    <script type="text/javascript" charset="utf-8">

    $(document).ready( function () {

      var jsonData = {};
          $.ajax({
            url: "http://www.json-generator.com/api/json/get/bUHEbjuIoi?indent=2",
            async: false,
            dataType: 'json',
            success: function(data) {
              jsonData = data;
            }
          });

      console.log(jsonData);

      var hideFromExport = [1, 2, 3]; /*<--- How i can custom this for each table individually ?? */

      var options = {
        responsive: true,
        bAutoWidth: true,
        dom: '<"top"lf>Bt<"bottom"pi><"clear">',
        scrollY: 400,
        scrollCollapse: true,
        jQueryUI: true,
        bProcessing: true,
        sScrollX: "70%",
        sScrollXInner: "100%",
        bScrollCollapse: true,
        bDestroy: true,
        searching: false,
        iDisplayLength: 25,
        buttons: [{ /*<--- How i can custom this for each table individually ?? */
                extend: 'copyHtml5',
                exportOptions: {
                  columns: function(idx, data, node) {
                    var isVisible = table.column(idx).visible();
                    var isNotForExport = $.inArray(idx, hideFromExport) !== -1;
                    return isVisible && !isNotForExport ? true : false;
                  }
                }
              },
              'excelHtml5', 'csvHtml5', 'pdfHtml5'
        ],
        language: {
            url: "https://cdn.datatables.net/plug-ins/1.10.12/i18n/French.json",
            buttons: {
                copy: 'Copier Tickets',
                copyTitle: 'Ajouté au presse-papiers',
                copyKeys: 'Appuyez sur <i>ctrl</i> ou <i>\u2318</i> + <i>C</i> pour copier les données du tableau à votre presse-papiers. <br><br>Pour annuler, cliquez sur ce message ou appuyez sur Echap.',
                copySuccess: {
                    _: 'Copiés %d rangs',
                    1: 'Copié 1 rang'
                }
            }
        }
      };    

      function initialize(jsonData) {
           /* --- TableA INIT --- */
           options.aaData  = jsonData.sig1_re;
           options.aoColumns = [
                { "mData": "Ticket_RT" },
                { "mData": "Cable_de_renvoi" },
                { "mData": "Longueur_de_ligne_(Selt)" },
                { "mData": "Res_LigneCoupee" },
                { "mData": "Ticket_fils" },
                { "mData": "Gamot_DateFermeture" },
                { "mData": "Numero_ND" },
                { "mData": "Gamot_DateFermeture" },
                { "mData": "Supprimer" }
           ];
           options.aoColumnDefs = [
                { "title": "Titre 1", "targets": 0 },
                { "title": "Titre 2", "targets": 1 },
                { "title": "Titre 3", "targets": 2 },
                { "title": "Titre 4", "targets": 3 },
                { "title": "Titre 5", "targets": 4 },
                { "title": "Titre 6", "targets": 5 },
                { "title": "Titre 7", "targets": 6 },
                { "title": "Titre 8", "targets": 7 },
                { "title": "Titre 9", "targets": 8 }

                /*{ "targets": 1, "render": $.fn.DataTable.render.ellipsis(5) }*/
           ];


          $("#tableA").dataTable(options);


          /* --- TableB INIT --- */          
          options.aaData = jsonData.bad_nd;
          options.aoColumns = [
                { "mData": "Ticket_RT" },
                { "mData": "Numero_ND" },
                { "mData": "Supprimer" }
          ];
          options.aoColumnDefs = [
               { "title": "Titre 01", "targets": 0 },
               { "title": "Titre 02", "targets": 1 },
               { "title": "Titre 03", "targets": 2 },

               { "targets": 1, "render": $.fn.DataTable.render.ellipsis(5) }
          ];


          $("#tableB").dataTable(options);
      }

      initialize(jsonData);

      var oTable = $('#tableA').DataTable(); /*<--- How i can custom this for each table individually ?? */
          $('#tableA').on('click', 'a.delete', function (e) {
              oTable.row($(this).parents('tr')).remove().draw();
      });

      // Permet de réduire les commentaires et ajouter tooltip
      $.fn.DataTable.render.ellipsis = function ( cutoff, wordbreak, escapeHtml ) {
          var esc = function ( t ) {
              return t
                  .replace( /&/g, '&amp;' )
                  .replace( /</g, '&lt;' )
                  .replace( />/g, '&gt;' )
                  .replace( /"/g, '&quot;' );
          };

          return function ( d, type, row ) {
              // Order, search and type get the original data
              if ( type !== 'display' ) {
                  return d;
              }

              if ( typeof d !== 'number' && typeof d !== 'string' ) {
                  return d;
              }

              d = d.toString(); // cast numbers

              if ( d.length < cutoff ) {
                  return d;
              }

              var shortened = d.substr(0, cutoff-1);

              // Find the last white space character in the string
              if ( wordbreak ) {
                  shortened = shortened.replace(/\s([^\s]*)$/, '');
              }

              // Protect against uncontrolled HTML input
              if ( escapeHtml ) {
                  shortened = esc( shortened );
              }

              return '<span class="ellipsis" title="'+esc(d)+'">'+shortened+'&#8230;</span>';
          };
      };

    });

    </script>
  </body>
</html>

解决方案:

经过大量研究后,我找到了通讯按钮选项的解决方案,现在效果很好!然后我添加了一个删除所选行的按钮。

我希望这段代码可以帮助像我这样的更多家伙!

享受:)

代码:

  <!DOCTYPE html>
  <html>
    <head>

      <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
      <link href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.css" rel="stylesheet" type="text/css" />
      <link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />    
      <link href="https://cdn.datatables.net/responsive/2.1.0/css/responsive.dataTables.css" rel="stylesheet" type="text/css" />
      <link href="https://cdn.datatables.net/buttons/1.2.2/css/buttons.dataTables.css" rel="stylesheet" type="text/css" />
      <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
      <link rel="stylesheet" type="text/css" href="css/bfm.css">

      <meta charset=utf-8 />
      <title>DataTables - JS Bin</title>
    </head>
    <body>
      <div class="container" style="width: 90%;">
        <div class="panel panel-danger" style="margin: 5px;">
            <div class="panel-heading">
              <h2 class="panel-title">
                <b>My Test</b>
              </h2>
            </div>
            <div class="panel-body">
              <div class="table-responsive">
                <table id="tableA" class="table table-striped table-hover dt-responsive display nowrap" cellspacing="0" width="100%"></table>

                <br />

                <table id="tableB" class="table table-striped table-hover dt-responsive display nowrap" cellspacing="0" width="100%"></table>    
              </div>
            </div>
        </div>
      </div>

      <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
      <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.js"></script>
      <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
      <script src="https://cdn.datatables.net/responsive/2.1.0/js/dataTables.responsive.js"></script>
      <script src="https://cdn.datatables.net/buttons/1.2.2/js/dataTables.buttons.js"></script>
      <script src="https://raw.githubusercontent.com/Stuk/jszip/master/dist/jszip.min.js"></script>
      <script src="https://raw.githubusercontent.com/bpampuch/pdfmake/master/build/pdfmake.min.js"></script>
      <script src="https://raw.githubusercontent.com/bpampuch/pdfmake/master/build/vfs_fonts.js"></script>
      <script src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.html5.min.js"></script>
      <script src="https://cdn.datatables.net/plug-ins/1.10.12/dataRender/ellipsis.js"></script>

      <script type="text/javascript" charset="utf-8">

      $(document).ready( function () {

        var jsonData = {}; // get the json object array from php
            $.ajax({
              url: "http://www.json-generator.com/api/json/get/bTKebXDGdK?indent=2",
              async: false,
              dataType: 'json',
              success: function(data) {
                jsonData = data;
              }
            });

        console.log(jsonData);

        var buttonCommon = { // set default export column 0 (first column)
                exportOptions: {
                    columns:[0]
                }
            };

        var options = { // set options for tables
              responsive: true,
              bAutoWidth: true,
              dom: '<"top"lf>Bt<"bottom"pi><"clear">',
              scrollY: 400,
              scrollCollapse: true,
              jQueryUI: true,
              bProcessing: true,
              sScrollX: "70%",
              sScrollXInner: "100%",
              bScrollCollapse: true,
              bDestroy: true,
              searching: false,
              iDisplayLength: 25,
              buttons: [
                  $.extend( true, {}, buttonCommon, {
                    header: false,
                    extend: 'copyHtml5'
                  }),
                  'excelHtml5', 'csvHtml5', 'pdfHtml5',
                  {
                    text: 'Delete',
                    action: function ( e, dt, node, config ) { // function to delete selected rows on click button
                        dt.data().rows('.selected').remove().draw( false );
                    }
                  }
              ],
              language: {
                  url: "json/French.json",
                  buttons: {
                      copy: 'Copy',
                      copyTitle: 'Ajouté au presse-papiers',
                      copyKeys: 'Appuyez sur <i>ctrl</i> ou <i>\u2318</i> + <i>C</i> pour copier les données du tableau à votre presse-papiers. <br><br>Pour annuler, cliquez sur ce message ou appuyez sur Echap.',
                      copySuccess: {
                          _: 'Copiés %d rangs',
                          1: 'Copié 1 rang'
                      }
                  }
              }
            };    

        function initialize(jsonData) {
             /* --- TableA INIT --- */
             options.aaData  = jsonData.sig1_re;
             options.aoColumns = [
                  { "mData": "Ticket_RT" },
                  { "mData": "Cable_de_renvoi" },
                  { "mData": "Longueur_de_ligne_(Selt)" },
                  { "mData": "Res_LigneCoupee" },
                  { "mData": "Ticket_fils" },
                  { "mData": "Gamot_DateFermeture" },
                  { "mData": "Numero_ND" },
                  { "mData": "Difference_de_date" }
             ];
             options.aoColumnDefs = [
                  { "title": "Titre 1", "targets": 0 },
                  { "title": "Titre 2", "targets": 1 },
                  { "title": "Titre 3", "targets": 2 },
                  { "title": "Titre 4", "targets": 3 },
                  { "title": "Titre 5", "targets": 4 },
                  { "title": "Titre 6", "targets": 5 },
                  { "title": "Titre 7", "targets": 6 },
                  { "title": "Titre 8", "targets": 7 }

                  /*{ "targets": 1, "render": $.fn.DataTable.render.ellipsis(5) }*/
             ];


            $("#tableA").dataTable(options);

            /* --- TableB INIT --- */          
            options.aaData = jsonData.bad_nd;
            options.aoColumns = [
                  { "mData": "Ticket_RT" },
                  { "mData": "Numero_ND" }
            ];
            options.aoColumnDefs = [
                 { "title": "Titre 01", "targets": 0 },
                 { "title": "Titre 02", "targets": 1 },

                 { "targets": 1, "render": $.fn.DataTable.render.ellipsis(5) } // call function to render + tooltip
            ];


            $("#tableB").dataTable(options);
        }

        initialize(jsonData);

        $('#tableA tbody').on( 'click', 'tr', function () { // set multi select rows
                $(this).toggleClass('selected');
        });

        $('#tableB tbody').on( 'click', 'tr', function () { // set multi select rows
                $(this).toggleClass('selected');
        });

        // Function to delimit render + tootil
        $.fn.DataTable.render.ellipsis = function ( cutoff, wordbreak, escapeHtml ) {
            var esc = function ( t ) {
                return t
                    .replace( /&/g, '&amp;' )
                    .replace( /</g, '&lt;' )
                    .replace( />/g, '&gt;' )
                    .replace( /"/g, '&quot;' );
            };

            return function ( d, type, row ) {
                // Order, search and type get the original data
                if ( type !== 'display' ) {
                    return d;
                }

                if ( typeof d !== 'number' && typeof d !== 'string' ) {
                    return d;
                }

                d = d.toString(); // cast numbers

                if ( d.length < cutoff ) {
                    return d;
                }

                var shortened = d.substr(0, cutoff-1);

                // Find the last white space character in the string
                if ( wordbreak ) {
                    shortened = shortened.replace(/\s([^\s]*)$/, '');
                }

                // Protect against uncontrolled HTML input
                if ( escapeHtml ) {
                    shortened = esc( shortened );
                }

                return '<span class="ellipsis" title="'+esc(d)+'">'+shortened+'&#8230;</span>';
            };
        };

      });

      </script>
    </body>
  </html>

1 个答案:

答案 0 :(得分:0)

我建议将表格与属性分开。如果您想在数据表中添加额外的列和按钮。您可以使用以下方法实现这一目标。

  1. 操作添加额外的列。
  2. fnRowCallback 方法中,将特定类添加到操作列。
  3. 点击操作的示例:

    jQuery('#datatable tbody').on('click', 'td.action', function () {
    
         //call custom method to format the data inside td.action column.
         data = {
                  'id': $(this).attr('cour_id')
                };
    
         tr.after(format(data)).show();
    });
    

    它将为每行创建具有特定行ID和属性的操作按钮,并且彼此之间不会发生冲突。

    希望它会有所帮助!