简体   繁体   中英

Two DataTables sourced from different APIs on the same page show the same data

I have two DataTables on the same web page with the same number of columns that are sourced from DIFFERENT APIs. If I add the class "grid" to one or the other the table displays with the correct data for that table. However, if I add the class "grid" to both, the data for the first table shows up on BOTH tables.

The class "grid" is a very complex DataTable that involves quite a bit of configuration but here is how "grid" is initialized:

var t = $(".grid").DataTable({
        iDisplayLength: 10,
        columnDefs: [{
            "searchable": false,
            "orderable": bOrderBy,
            "targets": 0
        }],
        order: [[0, orderDir]],
        ajax: {
            url: src,
            dataSrc: ""
        },
        columns: [
            {
                data: f1
            },
            {
                data: f2
            },
            {
                data: f3
            },
            {
                data: f4
            },
            {
                data: f5,
. . . "blah, blah, blah"
});

t.on('post-body.bs.table', function () {
        $('[data-toggle="tooltip"]').tooltip({
            container: 'body',
            placement: 'top'
        });
    });


    if (autoNum == "Y") {
        t.on('order.dt search.dt', function () {
            t.column(0, { search: 'applied', order: 'applied' }).nodes().each(function (cell, i) {
                cell.innerHTML = i + 1;
            });
        }).draw();
    }

How do I fix this?

Right now, it is applying the same DataTable instance to anything selected in your .grid selector which is why they are coming back the same. If the table options are the same, you can save this into a obj and then pass it to each call. Name the 2 tables with different id's or different classes

var dtOptions = {
    iDisplayLength: 10,
    columnDefs: [{
        "searchable": false,
        "orderable": bOrderBy,
        "targets": 0
    }],
    order: [[0, orderDir]],
    ajax: {
        url: src,
        dataSrc: ""
    },
    columns: [
        {
            data: f1
        },
        {
            data: f2
        },
        {
            data: f3
        },
        {
            data: f4
        },
        {
            data: f5,
. . . "blah, blah, blah"
};

$("#mytable1).DataTable(dtOptions);
$("#mytable2).DataTable(dtOptions);

You may need to change the ajax src for the 2nd table as you said they are coming from separate api's. You could possibly copy the options object and modify the ajax src if needed.

var dtOptions2= $.extend(true, {}, dtOptions);
dtOptions2.ajax.url = "somthing-else...";
$("#mytable2).DataTable(dtOptions2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM