簡體   English   中英

將Json數據作為對象發送到DataTables

[英]Sending Json data as an object into DataTables

我一直在嘗試使用DataTables。 但是在我的Ajax請求之后,我得到了一個Json對象,該對象無法傳遞到dataTables中。

我收到的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"
                } ]
            })
        }
    });

這是我目前得到的輸出

嘗試映射數據以刪除每個對象的attributes屬性

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

您幾乎在那里:

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在這里使用JSFiddle。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM