简体   繁体   English

在jQuery中向DataTable添加新行时出错

[英]Error while adding a new row to DataTable in jQuery

I have the dataSource defined as 我将dataSource定义为

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 现在当我尝试向dataTable添加新行时

$('#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 DataTables警告(表ID ='table1'):从数据源请求的行1001的未知参数'name'

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 . 当您尝试将objects array作为aaData插入时,该错误已经出现。 You must define which property of each object that correspond to a column through aoColumns : 您必须通过aoColumns定义与列对应的每个对象的哪个属性:

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

Now the mapping from object to aaData is OK. 现在从objectaaData的映射就可以了。 Note that if you use datatables 1.9.4 or above, mDataProp is renamed to mData (even though it will still work). 请注意,如果您使用数据表1.9.4或更高版本,则mDataProp将重命名为mData (即使它仍然可以工作)。 Next, 下一个,

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

Is wrong. 是错的。 How should dataTables know how it should handle that array? dataTables应该如何知道如何处理该数组? 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 : 这会在您的控制台中引发一个巨大的错误(您可能未曾见过,因为脚本已经在aaData : arr处停止了。正确的方法是在dataTable-object上调用fnAddData ,并与之前相同的方式插入数据aoColumns已定义的数据应插入:

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/ 请参阅上面的示例,您的代码将在此小提琴中工作-> http://jsfiddle.net/krs6f/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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