在表

时间:2018-01-20 13:23:05

标签: javascript jquery json

我在html表格中显示json数据时遇到问题。我相信它与我的json格式化真的很奇怪的事实有关(我无法改变它) 提前致谢。

{"name":["instance-5","instance-6"],"id"["1178823664323071067","5394281241544297728"],"ip":["35.189.8.115","35.201.16.102"],"status":["RUNNING","RUNNING"]}

<script> 

$( document ).ready(function() {
$.ajax({
    url: '/api/instance/list',
    type: 'get',
    dataType: 'json',
    error: function(data){
    },
    success: function(data){
        var tr = $('<tr>');
        tr.append('<td>' + data.name + '<td>');
        tr.append('<td>' + data.id + '<td>');
        tr.append('<td>' + data.ip + '<td>');
        tr.append('<td>' + data.status + '<td>');


        $('#application-table').append(tr);           
    }
});
});

</script>

<table id="application-table" class="aui">
<thead>
    <tr>
        <th width="20%">Instance Name</th>
        <th width="20%">ID</th>
        <th width="20%">IP</th>
        <th width="5%">Status</th>

    </tr>
</thead>

1 个答案:

答案 0 :(得分:2)

您的响应被格式化为每个属性都是它自己的数组,可能意味着name[0]与其他数组中所有其他[0]索引项相关。

因此,为了达到您的要求,您可以遍历响应并将属性中的所有值放在新行中的相同索引处,如下所示:

var data = {
  "name": ["instance-5", "instance-6"],
  "id": ["1178823664323071067", "5394281241544297728"],
  "ip": ["35.189.8.115", "35.201.16.102"],
  "status": ["RUNNING", "RUNNING"]
}

for (var i = 0; i < data.name.length; i++) {
  var tr = $('<tr>');
  tr.append('<td>' + data.name[i] + '<td>');
  tr.append('<td>' + data.id[i] + '<td>');
  tr.append('<td>' + data.ip[i] + '<td>');
  tr.append('<td>' + data.status[i] + '<td>');
  $('#application-table').append(tr);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="application-table"></table>

那就是说,我建议找一种方法来改变你的响应结构,以便在单个数组的每个项目中关联行数据,如下所示:

var data = [{
  "name": "instance-5",
  "id": "1178823664323071067",
  "ip": "35.189.8.115",
  "status": "RUNNING"
}, {
  "name": "instance-6",
  "id": "1178823664323071067",
  "ip": "35.201.16.102",
  "status": "RUNNING"
}]

var html = data.map(function(row) {
  return `<tr><td>${row.name}</td><td>${row.id}</td><td>${row.ip}</td><td>${row.status}</td></tr>`;
});
$('#application-table').append(html.join(''));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="application-table"></table>