在HTML表格中展示特殊格式JSON数据遇问题求助
Hey there! I see the issue you're facing—your JSON structure has each field as an array (one entry per instance), but your current JavaScript is just dumping the entire array into a single table cell. Let's fix that so each instance gets its own row in the table.
First, a quick note: Your sample JSON has a syntax error—"id" is missing a colon. The correct valid version should be:
{"name":["instance-5","instance-6"],"id":["1178823664323071067","5394281241544297728"],"ip":["35.189.8.115","35.201.16.102"],"status":["RUNNING","RUNNING"]}
Since you mentioned you can't modify the JSON format, I'll assume the backend returns valid JSON with this array-based structure.
The Problem with Your Current Code
Right now, you're appending one row that contains all instance names, all IDs, etc., in single cells. That's why you're seeing comma-separated values instead of individual rows for each instance. Plus, your original code had unclosed <td> tags, which breaks proper HTML structure.
Modified Solution Code
Here's the updated JavaScript that loops through each instance and creates a separate table row for each one:
<script> $( document ).ready(function() { $.ajax({ url: '/api/instance/list', type: 'get', dataType: 'json', error: function(data){ // Add basic error handling for debugging console.log("Error fetching instance data:", data); }, success: function(data){ // Get the total number of instances (all arrays should match in length) const instanceCount = data.name.length; // Loop through each index to build a row per instance for(let i = 0; i < instanceCount; 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>
Key Fixes & Explanations
- Per-instance row creation: We loop through each index
ito access the corresponding entry in every array (name, id, ip, status), building a unique row for each instance. - Valid HTML structure: Fixed the unclosed
<td>tags to ensure the table renders correctly. - Basic error handling: Added a console log to help debug if the API call fails.
Your HTML Table Structure (Unchanged)
Your existing table setup works perfectly with this solution:
<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> </table>
This will render each instance as a separate row in your table, with each value aligned to the correct header column.
内容的提问来源于stack exchange,提问作者Jamie Duke

