DataTables读取对象内的数组

时间:2017-03-03 13:23:44

标签: javascript jquery datatables

我的问题很简单:如何使用数据表读取对象内的数组?

对象

我想读取数组“data”:

{
  "success": true,
  "data": [
    {
      "id": "4",
      "tienda_id": "5",
      "tienda_nombre": "sad",
      "total": 123,
      "logo": null,
      "fecha": "2017-04-02T23:00:00.000Z"
    }
  ]
}

数据表

        var x.DataTable({
            "ajax" : myAjaxUrl,
            "columns": [{
                "data": "data.fecha" // this doesn't work
            }, {
                "data": "data.total"  // this doesn't work
            }, {
                "data": "data.logo"  // this doesn't work
            }],
              //..............
        });

谢谢@Sotjin我知道怎么读json那不是问题,问题出在列数据中:

       "columns": [{
            "data": "data.fecha" // this doesn't work
        }, {
            "data": "data.total"  // this doesn't work
        }, {
            "data": "data.logo"  // this doesn't work
        }],

数据表的ajax返回对象然后在列中迭代该对象并在数据表中显示数据"data": "data.fecha" // this doesn't work

例如:

 {
 "data": [
        {
          "id": "4",
          "tienda_id": "5",
          "tienda_nombre": "sad",
          "total": 123,
          "logo": null,
          "fecha": "2017-04-02T23:00:00.000Z"
        }]
}
//...
 "columns": [{
                "data": "data.fecha"
            }, {
                "data": "data.total" 
            }, {
                "data": "data.logo" 
            }],

这有效

{
  "success": true,
  "data": [
    {
      "id": "4",
      "tienda_id": "5",
      "tienda_nombre": "sad",
      "total": 123,
      "logo": null,
      "fecha": "2017-04-02T23:00:00.000Z"
    }
  ]
}

这不起作用

2 个答案:

答案 0 :(得分:0)

 var json = {
  "success": true,
  "data": [
    {
      "id": "4",
      "tienda_id": "5",
      "tienda_nombre": "sad",
      "total": 123,
      "logo": null,
      "fecha": "2017-04-02T23:00:00.000Z"
    }
  ]
}

阅读data属性:

json.data[0].fecha
json.data[0].logo
...

如果data中有多个对象,则可以运行循环以对每个对象执行某些操作:

json.data.forEach(function(obj) {
   console.log(obj);
});

答案 1 :(得分:0)

使用以下代码:

var x.DataTable({
   "ajax" : myAjaxUrl,
   "columns": [
      { "data": "fecha" }, 
      { "data": "total" }, 
      { "data": "logo" }
   ],
   // ...
});

有关详细信息,请参阅Ajax sourced data