从PHP使用多表填充DataTables Ajax Json对象


Populate DataTables Ajax Json object from PHP using multi tables

在我的项目中,我使用数据表来显示我的数据,这是从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>"
      }
    ]
  }

在我的第一次尝试中,我有一个JS文件为我的html中的每个表,这工作得很好,但我重复了很多相同的代码,每次调用JSON echo,所以我决定在一个JS文件中重新组合我的所有代码。

我设法导出几乎所有的表选项,但我有困难定义一些变量;一个是hideFromExport:当我点击"复制"按钮时,我只需要复制第一列的值。第二个问题是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. 动作增加一列。
  2. fnRowCallback方法中添加特定的类到action列。

点击动作示例:

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和属性的操作按钮,并且不会相互冲突。

希望对你有帮助!