close

Q: 使用dataTable ajax取得資料時,在render function去呼叫rowdata時出現"undefined"的問題

A: 因為在"columns"是使用object方式去給值 ex: { "data": "id" }

所以使用array方式去取值是取不到的 ex: row[1] <= 這時就會出現undefined

使用object直接取值即可 ex: row.id

--

轉自 https://datatables.net/forums/discussion/20388/trying-to-access-rowdata-in-render-function-with-ajax-datasource-getting-undefined

--

Trying to access rowdata in render function with ajax datasource, getting undefined

bicklebickle Posts: 8Questions: 0Answers: 0
 edited April 2014in DataTables 1.10
I'm getting an undefined value when I try to reference the row parameter in the render function. When I try the example at http://next.datatables.net/examples/advanced_init/column_render.html, that works fine. But when I switch to an ajax datasource, the row parameter is undefined. I have an example here: http://live.datatables.net/lijoyay/2/edit For the purposes of the example, I'm just joining the first 2 columns. 

Here's the debug data code for what I'm actually working on, in case it is of any relevance: ivoqan

Replies

  • allanallan Posts: 50,177Questions: 1Answers: 7,444 Site admin
    Thanks for the test case. You won't like it, but it looks like it is working as expected :-).

    The problem with the code is `row[1]` - that assumes the data is an array. But it isn't - you've given it an object, so there are no array indexes... You want to use something like `row.position` .

    Allan
  • bicklebickle Posts: 8Questions: 0Answers: 0
     edited April 2014
    Wow, I could've sworn I tried that. And yet I try it this morning and it worked like a charm.

    [quote]You won't like it, but it looks like it is working as expected[/quote]
    Heh, I fully expected that to be the case. I'm on a javascript/ajax crash course so this is all new to me. 

    Thanks again!

    If anyone wants a working example, this is what works with the example posted above:
    [code]$(document).ready(function() {
    $('#example').dataTable( {
    "ajax": "/ajax/objects.txt",
    "columns": [
    { "title": "Name & Position",
    "data": "name" },
    { "data": "position" },
    { "data": "office" },
    { "data": "extn" },
    { "data": "start_date" },
    { "data": "salary" }
    ],
    "columnDefs": [
    {
    "render": function ( data, type, row ) {
    return data +', '+ row.position;
    },
    "targets": 0
    }
    ]
    } );
    } );[/code]
This discussion has been closed.

--

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 dizzy03 的頭像
    dizzy03

    碎碎念

    dizzy03 發表在 痞客邦 留言(0) 人氣()