سؤال

I have the dataSource defined as

function getData(){
     var arr = [];
     for(var i=0; i<1000; i++){
          var obj = {
               'name': 'John', 'company' : 'ABC Corp', 'salary': '$x'
         };
         arr.push(obj);
     }
     return arr;
}

The table is being rendered as

var arr = getData();
$('#table1').dataTable({
      'aaData': arr,
      'aoColumns': [
           {'sTitle': 'name'},
           {'sTitle': 'company'},
           {'sTitle': 'salary'}
      ]
}}

Now when i try to add a new row to the dataTable as

$('#table1').dataTable.fnAddData([
      "&nbsp;", "&nbsp;", "&nbsp;"
]);

I get an error as

DataTables warning (table id = 'table1'): Requested unknown parameter 'name' from the data source for row 1001

What can be causing this?

هل كانت مفيدة؟

المحلول

The problem is not that you are trying to add a new row. The error appears already when you try to insert an array of objects as aaData. You must define which property of each object that correspond to a column through aoColumns :

var dataTable = $('#example').dataTable({
    aaData : arr,
    aoColumns: [
        {mDataProp: 'name'},
        {mDataProp: 'company'},
        {mDataProp: 'salary'}
    ]
});

Now the mapping from object to aaData is OK. Note that if you use datatables 1.9.4 or above, mDataProp is renamed to mData (even though it will still work). Next,

$('#table1').dataTable.fnAddData([
  "&nbsp;", "&nbsp;", "&nbsp;"
]);

Is wrong. How should dataTables know how it should handle that array? It raises a huge error in your console (which you probably have not seen, because the script halted already at aaData : arr. The correct way is to call fnAddData on your dataTable-object, and insert data in the same manner as you prior in aoColumns have defined data should be inserted :

dataTable.fnAddData([
  'a', 'b', 'c'
]);

Is wrong

dataTable.fnAddData(
  { name : "a", company : "b", salary : "c" }
);

Is correct. See the examples above and your code working in this fiddle -> http://jsfiddle.net/krs6f/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top