使用AJAX在DataTables中的子行

时间:2015-05-08 15:17:29

标签: javascript jquery ajax datatables

我正在尝试将子表与父表绑定。当子表的数据通过AJAX调用然后创建动态表时,我无法弄清楚如何做到这一点。

我已关注this

以下是我的代码。

$('#myTable tbody).on('click', 'td.details-control', function () {

        var tr = $(this).closest('tr');
        var row = $('#myTable').DataTable().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(format()).show();
            tr.addClass('shown');
        }
    });

function format() {

    $.ajax({
        type: 'GET',
        url: '@Url.Action("MyFunction", "Home")',
        data: { "Id": MyId },
        dataType: "json",
        async: false,
        success: function (data) {
            var list = data;
            $.each(list, function (index, item) {

                return '<table>.......<table />';

                //i need to loop across the list and create a dynamic table with tr and td


            });
        },
        error: function (result) {
            var error = JSON.stringify(result);
            throw "Error...";
        }
    });
}

1 个答案:

答案 0 :(得分:5)

$('#myTable tbody').on('click', 'td.details-control', function () {

    var tr = $(this).closest('tr');
    var row = $('#myTable').DataTable().row(tr);

    if (row.child.isShown()) {
        // This row is already open - close it

        row.child.hide();
        tr.removeClass('shown');
    }
    else {
        format(row.child);  // create new if not exist
        tr.addClass('shown');
    }
});

然后format()

function format(callback) {
    $.ajax({
        .... 
        //async: false, you can use async 
        success: function (data) {
            var list = data;
            var html = '';
            $.each(list, function (index, item) {
                ...
                //create <tr> <td> with loop
                html= '<tr><td>.......</tr>';
            });
            callback($('<table>' + html + '</table>')).show();
        },
        ...
    });
}

演示 jsfiddle