数据表 - 从服务器加载所有数据,但在数据表

时间:2017-12-11 10:58:32

标签: javascript php datatables

我在我的一个客户网站上有一个表,其中包含超过1500行,从SQL Server中提取数据。我正在使用DATATABLES来呈现数据。

问题是,当我第一次启动项目时,我从未想过我需要AJAX或服务器端处理"。所以我直接把所有数据都拉到HTML。因为我只有100-200行显示。

但现在,我有超过1500行,页面加载速度非常慢。我知道datatables可以处理更多,但我几乎使用了数据表的每个功能来打动我的客户。意味着要加载许多JavaScript代码行,例如调整函数大小,自定义搜索,导出表,子行,自动添加和删除css类,createdCell函数等等。

简而言之,执行SQL查询需要3秒钟,但渲染数据需要25秒。

  

我真正想做的是:从服务器加载所有数据(1500行),因为花了3秒钟。并且只渲染其中的100个(每页25个x 4)。然后再休息。

我如何克服这个问题?这是我处理数据表的JS代码:



$(document).ready(function() {

// Calculating table height
var calcDataTableHeight = function() {
    h = $('#sidebar-wrapper').height() - 120;
    return h;
};

    $("#menu-toggle").click(function(e) {
        e.preventDefault();
        $("#wrapper").toggleClass("active");
    });

    $('#tablo tfoot th').not(":eq(0)").each(function () {
      var title = $('#tablo tfoot th').eq($(this).index()).text();
      $(this).html('<input type="text" placeholder="' + title + '" />');
    });

    var defaultOptions =  {
    "initComplete": function () {
                var api = this.api();
                api.$('td').not(":eq(0)").dblclick( function () {
                    api.search( jQuery.fn.DataTable.ext.type.search.string(this.innerHTML) ).draw();
                    $('#clearf').addClass('filtrevar');
                } );
            },
    "columnDefs": [
        {
        "targets": [0],
        "width": "10"
        },
        {
        "targets": [1],
        "width": "80",
        "sType": "date-uk"
        },
        {
        "targets": [2],
        "width": "80"
        },
        {
        "targets": [3],
        "width": "40",
        "visible": false
        },
        {
        "targets": [4],
        "width": "200"
        },
        {
        "targets": [5],
        "width": "200"
        },
        {
        "targets": [6],
        "width": "80",
        "visible": false
        },
        {
        "targets": [7],
        "width": "80"
        },
        {
        "targets": [8],
        "width": "120"
        },
        {
        "targets": [11],
        "width": "80",
        "visible": false
        },
        {
        "targets": [16],
        "width": "80"
        },
        {
        "targets": [17],
        "width": "80",
        "visible": false
        },
        {
        "targets": [18],
        "width": "110",
        "visible": false
        },
        {
        "width": "90",
        "targets": [9],
            createdCell: function ( cell, cellData, rowData ) {
                if(parseInt(cellData) > 0) {
                  $(cell).html('<h5 style=" margin: 0px;"><span class="label label-success">'+cellData+'</span></h5>');
                } else {
                  $(cell).html('<h5 style=" margin: 0px;"><span class="label label-default">'+cellData+'</span></h5>');
                }
            }
        },
        {
        "width": "90",
        "targets": [10],
            createdCell: function ( cell, cellData, rowData ) {
                if(parseInt(cellData) > 0) {
                  $(cell).html('<h5 style=" margin: 0px;"><span class="label label-primary">'+cellData+'</span></h5>');
                } else {
                  $(cell).html('<h5 style=" margin: 0px;"><span class="label label-default">'+cellData+'</span></h5>');
                }
            }
        },
        {
        "width": "90",
        "targets": [12],
            createdCell: function ( cell, cellData, rowData ) {
                if(parseInt(cellData) > 0) {
                  $(cell).html('<h5 style=" margin: 0px;"><span class="label label-info">'+cellData+'</span></h5>');
                } else {
                  $(cell).html('<h5 style=" margin: 0px;"><span class="label label-default">'+cellData+'</span></h5>');
                }
            }
        },
        {
        "width": "90",
        "targets": [13],
            createdCell: function ( cell, cellData, rowData ) {
                if(parseInt(cellData) > 0) {
                  $(cell).html('<h5 style=" margin: 0px;"><span class="label label-warning">'+cellData+'</span></h5>');
                } else {
                  $(cell).html('<h5 style=" margin: 0px;"><span class="label label-default">'+cellData+'</span></h5>');
                }
            }
        },
        {
        "width": "130",
        "targets": [14],
            createdCell: function ( cell, cellData, rowData ) {
                if(parseInt(cellData) > 0) {
                  $(cell).html('<h5 style=" margin: 0px;"><span class="label label-danger">'+cellData+'</span></h5>');
                } else {
                  $(cell).html('<h5 style=" margin: 0px;"><span class="label label-default">'+cellData+'</span></h5>');
                }
            }
        },
        {
        "width": "90",
        "targets": [15],
            createdCell: function ( cell, cellData, rowData ) {
                if(parseInt(cellData) > 0) {
                  $(cell).html('<h5 style=" margin: 0px;"><span class="label label-primary">'+cellData+'</span></h5>');
                } else {
                  $(cell).html('<h5 style=" margin: 0px;"><span class="label label-default">'+cellData+'</span></h5>');
                }
            }
        },
    ],    
    "scrollX": true,
    "sScrollY": calcDataTableHeight(),
    "scrollCollapse": true,
    "autoWidth": false,
    "lengthMenu": [[25, 50, 100, -1], [25, 50, 100, "Tümü"]],
    "bInfo" : false,
    "language": {
        "lengthMenu": "_MENU_",
        "zeroRecords": "Kayıt Bulunamadı",
        "info": "Toplam _TOTAL_ kayıttan, _START_ ve _END_ arası gösteriliyor.",
        "infoEmpty": "Herhangi bir kayıt yok.",
        "infoFiltered": "(_MAX_ toplam kayıttan filtrelenenler gösterilmektedir.)",
        "paginate": {
            "first": "İlk",
            "previous": "Önceki",
            "next": "Sonraki",
            "last": "Son"
            },
        "oAria": {
            "sSortAscending": ": Azalan Sırada",
            "sSortDescending": ": Artan Sırada"
            },
        "sLoadingRecords": "Kayıtlar Yükleniyor...",
        "sProcessing": "Lütfen Bekleyin...",
        "search": '_INPUT_',
        "searchPlaceholder": "        Arama Yapın...",
        "orderCellsTop": true,
        "buttons": {
            "copyTitle": "Panoya Kopyalandı",
            "copySuccess": {
                "_": '%d satır kopyalandı',
                "1": '1 satır kopyalandı'
            }
        }
    }
    };

defaultOptions.sScrollY = calcDataTableHeight();
var table = $('#tablo').DataTable(defaultOptions);

//** Secilen satırı renklendirmek için
$('#tablo tbody').on( 'click', 'tr', function () {
        if ( $(this).hasClass('selected') ) {
            $(this).removeClass('selected');
        }
        else {
            table.$('tr.selected').removeClass('selected');
            $(this).addClass('selected');
        }
    } );
 
    $('#button').click( function () {
        table.row('.selected').remove().draw( false );
    } );


    /* Formatting function for row details - modify as you need */
    function format(value) {
          return '<div id="childtr">' + value + '</div>';
      }
     
// Event listener - click veya diğer fonksiyonlar için
      $('#tablo').on('click', 'td.details-control', function () {
          var tr = $(this).closest('tr');
          var row = table.row(tr);

          if (row.child.isShown()) {
              row.child.hide();
              tr.removeClass('shown');
          } else {
              row.child(format(tr.data('child-value'))).show();
              tr.addClass('shown');
          }
      });


    // Aramayı Yap
    table.columns().every( function () {
        var that = this;
 
        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( jQuery.fn.DataTable.ext.type.search.string( this.value ) )
                    .draw();
                        var icerik = $(this).val().length;
                        if (icerik == 0) {
                            $('#clearf').removeClass('filtrevar');    
                        } else {
                            $('#clearf').addClass('filtrevar');
                        }
            }
        } );
    } );

// Genel Arama
$('#tablo_filter input').attr('id', 'globalAra');
$('#tablo_filter input').keyup(function() {
  table
    .search(
      jQuery.fn.DataTable.ext.type.search.string(this.value)
    )
    .draw();
    var icerik = $('#globalAra').val().length;
    if (icerik == 0) {
        $('#clearf').removeClass('filtrevar');    
    } else {
        $('#clearf').addClass('filtrevar');
    }
});


// Kaydet Butonlari
var kaydedin = new $.fn.dataTable.Buttons( table, {
"buttons": [
    {
            "extend": "excelHtml5",
            "text": "Excel'e Kaydet",
            "class": "excel"
        },
    {
            "extend": "pdfHtml5",
            "text": "PDF Kaydet",
            "class": "pdf",
            "orientation": 'landscape'
        },
    {
            "extend": "copyHtml5",
            "text": "Panoya Kopyala",
            "class": "copy"
        }
    ]
});
kaydedin.container().appendTo('#sol-menu-tablo-kaydet');


var solsutunlar = new $.fn.dataTable.Buttons( table, {
"buttons": [
     {
         "extend": 'colvis',
         "text": '<span class="glyphicon glyphicon-check" aria-hidden="true"> </span> Sütunları Aç / Kapat',
         "collectionLayout": 'fixed three-column'
     }
    ]
});
solsutunlar.container().appendTo('#sol-menu-sutunlar');

var solgorunum = new $.fn.dataTable.Buttons( table, {
"buttons": [
         {
            "text": '<span class="glyphicon glyphicon-retweet" aria-hidden="true"> </span> <span id="gorunum-deg">Standart Görünüme Geç</span>',
            "className": 'koyu',
            action: function ( e, dt, node, config ) {
                table.rows().every( function () {
                    this.child.hide();
                    this.nodes().to$().removeClass('shown');
                });
                var zozo =  table.column( 0 ).visible();
                if (zozo) {
                    table.column( 0 ).visible( false, false );
                    table.column( 3 ).visible( true, true );
                    table.column( 6 ).visible( true, true );
                    table.column( 11 ).visible( true, true );
                    table.column( 17 ).visible( true, true );
                    table.column( 18 ).visible( true, true );
                    table.columns.adjust().draw( true );
                } else if (!zozo) {
                    table.column( 0 ).visible( true, true );
                    table.column( 3 ).visible( false, false );
                    table.column( 6 ).visible( false, false );
                    table.column( 11 ).visible( false, false );
                    table.column( 17 ).visible( false, false );
                    table.column( 18 ).visible( false, false );
                    table.columns.adjust().draw( true );
                }
            }
        }
    ]
});
solgorunum.container().appendTo('#sol-menu-gorunum');

$("#sag-ust-pagination").append($(".dataTables_paginate"));
$("#sol-ust-ara").append($(".dataTables_filter"));
$("#sol-ust-length").append($(".dataTables_length"));

//Pre loader ve Tablo Yüksekliği
$(window).load(function() {
        // Animate loader off screen
        $(".se-pre-con").fadeOut("slow");
        $('div.dataTables_scrollBody').css('min-height',calcDataTableHeight());
    });


// Tüm filtreleri temizleme

    table.columns().every( function () {
        var that = this;
 
        $('#clearf').on( 'click', function () {
        $('input[type=search]').val('');
        $('input[type=text]').val('');
        
        if ( that.search() !== this.value ) {
            that
                .search("")
                .draw();
        $('#clearf').removeClass('filtrevar');       
        }
        
        $("#tablo").DataTable().search("").draw();

        } );
    } );

/* TARİH SORT ETMEK İÇİN */

jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"date-uk-pre": function ( a ) {
    var ukDatea = a.split('.');
    return (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;
},

"date-uk-asc": function ( a, b ) {
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},

"date-uk-desc": function ( a, b ) {
    return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}
} );


// Türkçe Karakter Sorunu
jQuery.fn.DataTable.ext.type.search.string = function ( data ) {
    return ! data ?
        '' :
        typeof data === 'string' ?
            data
                .replace(/i/g, 'İ')
                .replace(/ı/g, 'I') :
            data;
};


// Full Screen için
$('#ful').click(function(){
var i = document.body;

// full screen
if (i.requestFullscreen) {
    i.requestFullscreen();
} else if (i.webkitRequestFullscreen) {
    i.webkitRequestFullscreen();
} else if (i.mozRequestFullScreen) {
    i.mozRequestFullScreen();
} else if (i.msRequestFullscreen) {
    i.msRequestFullscreen();
}
if((window.fullScreen) || (window.innerWidth == screen.width && window.innerHeight == screen.height)) {
if (document.exitFullscreen) {
    document.exitFullscreen();
} else if (document.webkitExitFullscreen) {
    document.webkitExitFullscreen();
} else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
} else if (document.msExitFullscreen) {
    document.msExitFullscreen();
}
}

});

// Resize olduğunda tekrar boy hesabı yapıyor.
$(window).resize(function(){  
    $('div.dataTables_scrollBody').css('max-height',calcDataTableHeight());
    table.draw();
});


});
&#13;
&#13;
&#13;

以下是Chrome Performance的截图:

enter image description here

  

请注意,我没有时间和资源来更改整个架构,例如&#34;服务器端处理&#34;或使用AJAX。

     编辑:我意识到有一部分代码会减慢整个过程。我现在完全没有问题。虽然我仍然想知道是否有办法渲染部分HTML。

0 个答案:

没有答案