将数据填充到数据表的列中

时间:2017-01-30 13:17:12

标签: jquery json datatables

我从服务器获取json对象响应,但无法将数据呈现为列。 感谢您的帮助。

JSON OBJECT RESPONSE:
{
"CHD2": {
"POSName": "CHANDIGARH INDU. AREA-I",
"HODB": "QSR_PHASE-I_CHANDIGARH"
},
"D002": {
"POSName": "DEHRADUN-ASTLEY HALL",
"HODB": "QSR_DEHRADUN_ASTLEY"
},
"J002": {
"POSName": "VAISHALI NAGAR",
"HODB": "QSR_VAISHALI_NAGAR"
}
}

JQUERY SCRIPT

<script>
    $(document).ready(function() {
    console.log('Initializing tables...');
    var <a href="//legacy.datatables.net/ref#aaData">aaData</a> = [];
        $('#dataTables-example').DataTable({
            responsive: true,
            processing: true,
            serverSide: true,
            data : aaData,
            ajax: {
                url:'http://localhost:81/reporting/outletList.php',
                type:'POST',
                dataType:'json',
                dataSrc : "",
                error: function(errorThrown){
                    alert(errorThrown);
                    alert("There is an error with AJAX!");
                },
            "success": function(data) {
                                console.log(data);
                aaData.push([
                        data['CHD2'].POSName,
                        data['CHD2'].HODB
                    ]);
                aaData.push([
                    data['D002'].POSName,
                    data['D002'].HODB
                ]);
                data = aaData;
                console.log(data);
            }},
            /*columns: [
                { data: "POSName"},
                { data: "HODB"}
            ],*/
            "language": {
            "zeroRecords": "No records to display"
            }
            })
        });
    </script>



<div class="panel-body">
     <table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example">
     <thead>
     <tr>
     <th>POSName</th>
     <th>HODB</th>
     </tr>
     </thead>

仍然无法正常工作。 Chrome的开发人员工具中存在JSON对象响应,但表中没有填充数据。

1 个答案:

答案 0 :(得分:0)

这样的事情应该有效:

let data = {
    "CHD2": {
      "POSName": "CHANDIGARH INDU. AREA-I",
      "HODB": "QSR_PHASE-I_CHANDIGARH"
    },
    "D002": {
      "POSName": "DEHRADUN-ASTLEY HALL",
      "HODB": "QSR_DEHRADUN_ASTLEY"
    },
    "J002": {
      "POSName": "VAISHALI NAGAR",
      "HODB": "QSR_VAISHALI_NAGAR"
    }
  },
  dataArray = [];

for (let item in data) {
  let row = {
    "Name": item
  };
  for (let element in data[item]) {
    console.log(data[item][element]);
    row[element] = data[item][element];
  }
  dataArray.push(row);
}
console.log(dataArray);

完成后rows代表您的数据。工作JSFiddle https://jqueryui.com/dialog/#default