2017-04-01 39 views
0

我一直在尝试使用DataTables。但是在我的Ajax请求之后,我得到了一个Json对象,我无法传入数据表。将Json数据作为对象发送到DataTable中

JSON对象我收到如下

{"data": [{"attributes": {"purchasedate": "04/01/2017", "medication": "meds", "cost": 100.0, "expirydate": "04/03/2017", "quantity": 100.0}, "type": "medical_inventory"}, {"attributes": {"purchasedate": "04/01/2017", "medication": "Extra Meds", "cost": 100.0, "expirydate": "04/02/2017", "quantity": 100.0}, "type": "medical_inventory"}, {"attributes": {"purchasedate": "04/01/2017", "medication": "Extra Super Meds", "cost": 267.0, "expirydate": "04/11/2017", "quantity": 250.0}, "type": "medical_inventory"}], "links": {"self": "/medical_inventory/"}} 

以下是我的HTML代码

<table id="myTable" class="display" cellspacing="0" width="90%"> 
    <thead> 
     <tr> 
      <th>Medication</th> 
      <th>Medication Quantity</th> 
      <th>Mediaction Cost</th> 
      <th>Purchase Date</th> 
      <th>Expiry Date</th> 
     </tr> 
    </thead> 
    <tfoot> 
     <tr> 
      <th>Medication</th> 
      <th>Medication Quantity</th> 
      <th>Mediaction Cost</th> 
      <th>Purchase Date</th> 
      <th>Expiry Date</th> 
     </tr> 
    </tfoot> 
</table> 

Ajax请求我做的是以下

$(document).ready(function() { 
     $.ajax({ 
      url : '/api/medical_inventory/', 
      type : 'GET', 
      dataType : 'json', 
      success : function(data) { 
       assignToEventsColumns(data); 
      } 
     }); 

     function assignToEventsColumns(data) { 
      var table = $('#myTable').dataTable({ 
       "bAutoWidth" : false, 
       "aaData" : data, 
       "columns" : [ { 
        "data" : "medication" 
       }, { 
        "data" : "quantity" 
       }, { 
        "data" : "cost" 
       }, { 
        "data" : "purchasedate" 
       }, { 
        "data" : "expirydate" 
       } ] 
      }) 
     } 
    }); 

This is the output i am currently getting

+0

什么是“属性”属性? – charlietfl

+0

这是我得到的Json返回格式..我不知道如何解析它到dataTables所需的类型。 –

回答

0

你是非常接近那里的attributes属性:

function assignToEventsColumns(data) { 
    var table = $('#myTable').dataTable({ 
     "bAutoWidth": false, 
     "aaData": data.data, 
     "columns": [{ 
      "data": "attributes.medication" 
     }, { 
      "data": "attributes.quantity" 
     }, { 
      "data": "attributes.cost" 
     }, { 
      "data": "attributes.purchasedate" 
     }, { 
      "data": "attributes.expirydate" 
     }] 
    }) 
} 

所有你缺少的是你的JSON的结构,你需要添加attributes.为以及您的data.data:-D.Working JSFiddle here

0

尝试映射数据删除的每个对象

success : function(data) { 
    data.data = data.data.map(function(item){ 
     return item.attributes; 
    }); 
    assignToEventsColumns(data); 
} 
相关问题