【问题标题】:DataTables read array inside objectDataTables读取对象内的数组
【发布时间】:2017-07-23 15:12:24
【问题描述】:

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

对象

我想读取数组“数据”:

{
  "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"
    }
  ]
}

这不起作用

【问题讨论】:

    标签: javascript jquery datatables


    【解决方案1】:
     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);
    });
    

    【讨论】:

    • @JoseLuis 我也做了一些编辑,如果json.data 中只有一个对象,json.data[0].fecha 就是你需要的东西
    • 是的,但我没有只有 1 个对象,我只是在示例中显示了 1 个
    • @JoseLuis 是你需要的吗? (编辑),你想要来自多个对象的这 3 个元素吗?
    • 没有,因为我使用 DataTables 的 ajax 方法,如果我使用你的示例,我必须创建另一个 ajax。
    【解决方案2】:

    使用下面的代码:

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

    更多信息请参见Ajax sourced data

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-25
      • 2014-08-08
      相关资源
      最近更新 更多