简体   繁体   English

来自AJAX源的JQuery数据表行数据

[英]JQuery Datatables Row Data From AJAX Source

In the past I've always used this to get a hidden column's data. 过去,我一直使用它来获取隐藏列的数据。 I would hide the column with a css class, but the responsive feature doesn't work well with these. 我会使用CSS类隐藏该列,但响应功能不适用于这些类。

var td = $('td', this);
var ID = $(td[0]).text();

So I found an alternative, by hiding the columns with these classes with the responsive feature. 因此,我找到了一种替代方法,即使用响应功能将这些类的列隐藏起来。

"columnDefs": [
    //Responsive classes
    { className: 'never', targets: 0 }, //Hide on all devices
    { className: 'all', targets: 1 },   //Show on all devices
]

and then I use either one of these. 然后我使用其中之一。

var rowData = oTable1.fnGetData(this);
var rowData = oTable1.api().row(this).data();

//Grab the first indexed item in the list
var ID = rowData[0];

That works well if you don't have an AJAX source. 如果您没有AJAX来源,则效​​果很好。 It will return a comma separated list of the row data. 它将返回用逗号分隔的行数据列表。 However, when I try to use this with an AJAX source I just get [object Object] back (instead of a comma separated list) if I output the rowData variable in an alert. 但是,当我尝试将其与AJAX源一起使用时,如果我在警报中输出rowData变量,则只会得到[object Object](而不是逗号分隔的列表)。

How do I get the row data out of a table with an AJAX source? 如何使用AJAX源从表中获取行数据?

It seem to be stored as string so [1, 2, 3] became [object Object] when you turn it into string. 它似乎存储为字符串,所以当您将其变成字符串时,[1、2、3]成为[object Object]。 Do yourString = yourList.join(',') and store yourString to keep the coma-separated string. 执行yourString = yourList.join(',')并存储yourString以保持逗号分隔的字符串。

For an object: 对于对象:

yourString = (function () {
  var list = [];
  for(var i in yourList)
    if(yourList.hasOwnProperty(i))
      list.push(yourList[i]);
  return list.join(',');
})();

The function is not needed, it's just to limit the variables scope. 该函数不是必需的,仅用于限制变量范围。

I ended up using an answer I found here. 我最终使用了在这里找到的答案。 Converting a JS object to an array 将JS对象转换为数组

I can pull the entire row data from the table with this. 我可以以此从表中提取整个行数据。

 var rowData = oTable1.api().row(this).data();

In the console log I can see that it returns a javascript object like this. 在控制台日志中,我可以看到它返回了这样的javascript对象。

 Object { id="123456", full_name="Samuel Smith", Last_name="Smith" }

I use this function to convert the object into an array. 我使用此函数将对象转换为数组。

var array = $.map(rowData, function (value, index) {
        return [value];
    });

In the console log, my array would appear like this. 在控制台日志中,我的阵列将如下所示。

["123456", "Samuel Smith", "Smith"]

I can then extract any item from the array like this. 然后,我可以像这样从数组中提取任何项目。

alert(array[0]);

Simplifying madvora's example: 简化madvora的示例:

var rowData = oTable1.api().row(this).data().to$();
rowDataArray = rowData.toArray();

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

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