jQuery DataTables fnrender with objects

2019-02-17 18:42发布

问题:

I'm using jQuery DataTable to form a table out of this "data.txt":

{ "aaData" : [  
{       
    "ftitle": "Test1",
    "link": "http://server.com/test1/",
    "fname": "test1.pdf",
    "fid": "test1_353752165.pdf"
},
{       
    "ftitle": "Test2",
    "link": "http://server.com/test2/",
    "fname": "test2.pdf",
    "fid": "test2_353754257.pdf"
} ] }

This is my js code:

$('#example').dataTable( {
    "bProcessing": true,
    "sAjaxSource": "data/data.txt",
    "aoColumns": [
        {   "sClass": "center",
            "fnRender": function( oObj ) {
                return oObj.aData[0]+' '+ oObj.aData[2]; 
            } 
        },
        { "mDataProp": "fid", "sClass": "center" },
        { "mDataProp": "fname", "sClass": "center" }
    ],
} );

I just want to get the actual data with .aData of fnrender() but this works only with array-only data. What I get now is "undefined undefined", if I use a .txt with just array data it works fine.

I think I dont get it right how to use fnrender proberly, especially when working with objects.

回答1:

You're getting "undefined" because oObj.aData is an object, not an array, and there is no "0" field. Use syntax like this:

oObj.aData.link

or

oObj.aData["link"]

Full example (only modified fnRender return value):

$('#example').dataTable( {
    "bProcessing": true,
    "sAjaxSource": "data/data.txt",
    "aoColumns": [
        {   "sClass": "center",
            "fnRender": function( oObj ) {
                return '<a href="' + oObj.aData.link + '">' + oObj.aData.ftitle + '</a>';
            } 
        },
        { "mDataProp": "fid", "sClass": "center" },
        { "mDataProp": "fname", "sClass": "center" }
    ],
} );