building master-details grids using jquery datatab

2019-08-04 18:43发布

i'm using jQuery datatable as grid now i want to display master details (orders - order details) depending on master ID (ajax call to create the detail table) all i found https://datatables.net/examples/api/row_details.html which is static string is my request possible ?

thank you

1条回答
Lonely孤独者°
2楼-- · 2019-08-04 18:45

You can do ajax request before render extended row info.

Create a function that accept row info and callback which will render extended row info.

Inside a function do ajax callback and on success call render callback with formatted data.

Code example base on example link code:

/* Formatting function for row details - modify as you need */
function format ( d ) {
    // `d` is the original data object for the row
    return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
        '<tr>'+
            '<td>Full name:</td>'+
            '<td>'+d.name+'</td>'+
        '</tr>'+
        '<tr>'+
            '<td>Extension number:</td>'+
            '<td>'+d.extn+'</td>'+
        '</tr>'+
        '<tr>'+
            '<td>Extra info:</td>'+
            '<td>And any further details here (images etc)...</td>'+
        '</tr>'+
    '</table>';
}

function loadAjaxInfo(data, callback) {
    $.ajax({
      ...
      data: {/*Put your request needle here*/},
      ...
      success: function(response){
        callback(format(response));
      }
    })
}
 
$(document).ready(function() {
    var table = $('#example').DataTable( {
        "ajax": "../ajax/data/objects.txt",
        "columns": [
            {
                "className":      'details-control',
                "orderable":      false,
                "data":           null,
                "defaultContent": ''
            },
            { "data": "name" },
            { "data": "position" },
            { "data": "office" },
            { "data": "salary" }
        ],
        "order": [[1, 'asc']]
    } );
     
    // Add event listener for opening and closing details
    $('#example tbody').on('click', 'td.details-control', 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 {
          loadAjaxInfo(row.data(), function(formattedContent){
            // Open this row
            row.child(formattedContent).show();
            tr.addClass('shown');
          });
        }
    } );
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

查看更多
登录 后发表回答