Assign ID to datatable row from json data

2019-08-02 08:45发布

问题:

i'm new to datatable jquery plugin. I got stuck with this for more than 2 days. I have a Json Data, i still cant load the table and i also want to assign first column to be id of the row

Here is html:

<table cellpadding="0" cellspacing="0" border="0" class="display"
    id="accDetailTable">
    <thead>
        <tr>
            <th>Currency</th>
            <th>Current/Savings Account No.</th>
            <th>Securities Account No.</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

and my initialization

var oTable=$('#accDetailTable').dataTable( {
            "bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": contextPath + "/user/investorAjax?method=getInvestorAccDetailList",
            "iDeferLoading": 57,
    } );

Return jsonData from server :

    {"sEcho":1,"iColumns":4,"iTotalRecords":16,"iTotalDisplayRecords":16,
"aaData":
    [{"DT_RowId":2032,"currency":1,"currentAccNo":"aa","secureAccNo":"aa"},
    {"DT_RowId":2033,"currency":1,"currentAccNo":"111","secureAccNo":"111"},
    {"DT_RowId":2034,"currency":1,"currentAccNo":"a","secureAccNo":"aa"},
    ]}
}

But it always hit :

DataTables warning (table id = 'accDetailTable'): Added data (size undefined) does not match known number of columns (3)

回答1:

Your datatables is waiting for three entries per line and you give it four. In your table declaration (in html part) specify a new header cell <th> at the beginning of your row. You will put ids in it. Then after your dataTables initialization you can hide the first column using fnSetColumnVis(index, visibility) function :

oTable.fnSetColumnVis(0, false); //It will hide your first column

Doing that each row is containing his id (DT_RowId) but not displaying it.



回答2:

It's kind of easy. Let's just do a tiny change, since you want the first column contains id, you may need to use fnRender, please check the api of datatables, I didn't add this part of code:

var oTable=$('#accDetailTable').dataTable({
    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": contextPath + "/user/investorAjax?method=getInvestorAccDetailList",
    "aoColumns":[
        {"mDataProp":"currency"},
        {"mDataProp":"currentAccNo"},
        {"mDataProp":"secureAccNo"}
    ]
});