我在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>发布于 2018-01-20 21:26:37
响应的格式是每个属性都是它自己的数组,这可能意味着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>
https://stackoverflow.com/questions/48356639
复制相似问题