datatables - 通过ajax将数据预加载到数组执行多个连接

时间:2015-06-05 12:37:11

标签: jquery datatables

this教程之后我最终得到了这段代码(它基本上将外部文件中的子行内容加载到数组中):

/* Formatting function for row details - modify as you need */
function format ( d ) {
    // `d` is the original data object for the row
    // carica il template del dettaglio
    $.ajax ({
        async: false,
        type: "POST",
        url: "incaricodetail.html",
        cache: false,
        success: function(data){
            templateHtml = data; 
        }
    });
    var template = $.templates(templateHtml);
    var htmlOutput = template.render(d);

    return htmlOutput;
}

$(document).ready(function() {

    $.fn.dataTable.moment( 'DD/MM/YYYY' ); 
    var dettagli = []; 
    var table = $('#tabellaDati').DataTable( {
        "data": <?= json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));?>,  
        "columns": [
            {
                "className":      'details-control',
                "orderable":      false,
                "data":           null,
                "defaultContent":
                    '<a class="btn btn-xs" href="incarico_edit.php?id=<?=$id;?>&pageFrom=<?=pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME ); ?>" title="Modifica"><span class="glyphicon glyphicon-edit"></span></a>'+
                    '<a class="btn btn-xs delete-object" href="delete.php?id=<?=$row["id"]?>" delete-id="{$id}"" title="Elimina"><span class="glyphicon glyphicon-trash"></span></a>'+
                    '<a class="btn btn-xs" href="#" id="mostraDettaglio" title="dettaglio"><span class="glyphicon glyphicon-plus"></span></a>',
                    "render": function(data, type, row, meta) {
                        dettagli[meta.row] = format(data);
                    }

           },
           { "data": "id" },
           { "data": "protocollo" },
           { 
              "data": "dataIncarico",
              "type": "date",
              "dateFormat": "dd-mm-yyyy"
           }

        ],
        "order": [[1, 'asc']]
    });

    // Add event listener for opening and closing details
    $('#tabellaDati tbody #mostraDettaglio').on('click', function () {
        var tr = $(this).closest('tr');
        var row = table.row( tr );

        if ( row.child.isShown() ) {
            // This row is already open - close it
            row.child.hide();
            tr.removeClass('shown');
        }
        else {
            // Open this row
            row.child(dettagli[row.index()]).show();
            tr.addClass('shown');
        }
    } );
} );

我不知道为什么,但是对文件incaricodetail.html的ajax调用已完成三次(例如,对于两条记录,我有6个POST连接)。

DataTables调试器代码:onucak

真的可以吗? 亚历

1 个答案:

答案 0 :(得分:1)

初始化后,多次调用render

  • 显示
  • 排序
  • 过滤
  • 类型(检测)

那是每一行!您可以通过type参数检查渲染调用的类型。一个合格的猜测是你的渲染函数在typedisplayfilter上调用 - 你有2行,它会给format()函数调用6次,并且6个POST连接,因为您已关闭cache

你可以简单地避免这种情况:

render: function(data, type, row, meta) {
   if (typeof dettagli[meta.row] == 'undefined') {
      dettagli[meta.row] = format(data);
   }
}

为什么使用不同的type多次调用渲染?
因此,您可以为不同目的返回不同的数据。假设您有一些HTML包含一个复选框作为显示,对于排序您可以传递0,对于过滤您可以传递是/否,对于您可以传递数字的类型。

<强>更新即可。在dettagli[]而不是initComplete()中初始化render()

var table = $('#example').DataTable({
    initComplete : function() {
        var api = this.api(),
            rowCount = api.data().length;
        for (var i=0;i<rowCount;i++) {
            dettagli[i] = format(api.row(i).data()[0]);
        }    
    }        
});

这应与dettagli[meta.row] = format(data);相同,即调用format(),每行包含#0列的内容。

您还应该考虑只加载incaricodetail.html一次。为什么每次都要反复加载?似乎incaricodetail.html的内容不会改变,所以

也是如此
var template;
$.get("incaricodetail.html", function(html) {
   template = $.templates(html);
});

function format ( d ) {
   return template.render(d);
}

不完全一样吗?