如何使用JavaScript/jQuery加载JSON前5项数据到HTML表格
draws.json前5条数据渲染表格失败修复方案
核心错误诱因
以下是这类场景下最容易导致无行插入的问题点,按出现概率排序:
- DOM节点选取错误:未定位到表格下的
<tbody>节点,直接往table根节点插入行不符合DOM解析规则,浏览器不会正常渲染 - 嵌套结构取值错误:JSON解析完成后,
history数组的取值路径和实际结构不匹配(比如外层多包了一层data字段、字段名大小写错误),拿到的不是预期数组 - 数据结构拆解错误:单条数据中20位号码是嵌套数组,未做展开就直接拼接行内容,导致列数和预设的22列表头不匹配
- 执行时序错误:渲染逻辑写在XMLHttpRequest异步回调外,请求还未返回就执行了空数据渲染
- 节点挂载缺失:动态创建的tr/td节点没有最终append到tbody节点上,只创建了节点未加入DOM树
可直接运行的实现代码
HTML基础结构(和预设表头一致)
<table id="draws_table" border="1" cellpadding="4" cellspacing="0"> <thead> <tr> <th>日期</th> <th>时间</th> <th>N1</th><th>N2</th><th>N3</th><th>N4</th><th>N5</th> <th>N6</th><th>N7</th><th>N8</th><th>N9</th><th>N10</th> <th>N11</th><th>N12</th><th>N13</th><th>N14</th><th>N15</th> <th>N16</th><th>N17</th><th>N18</th><th>N19</th><th>N20</th> </tr> </thead> <tbody></tbody> </table>
原生JavaScript实现(无需jQuery)
function formatToTable(historyData) { // 仅截取前5条数据渲染 const renderData = historyData.slice(0, 5); const tbody = document.querySelector('#draws_table tbody'); // 清空 tbody 原有内容,避免重复渲染 tbody.innerHTML = ''; renderData.forEach(singleDraw => { // 解构单条数据,自动丢弃末尾两个不需要的数值字段 const [date, time, numberArr] = singleDraw; const tr = document.createElement('tr'); // 拼接日期、时间、20位号码为完整行数据,总长度正好22,和表头一一对应 const rowContent = [date, time, ...numberArr]; rowContent.forEach(cellValue => { const td = document.createElement('td'); td.textContent = cellValue; tr.appendChild(td); }); tbody.appendChild(tr); }); } // 发起JSON文件请求 const xhr = new XMLHttpRequest(); xhr.open('GET', 'draws.json', true); xhr.onload = function() { if (xhr.status < 200 || xhr.status >= 300) return console.error('请求失败,状态码:', xhr.status); try { const res = JSON.parse(xhr.responseText);
注意:如果你的draws.json存在外层嵌套,比如返回结构为{code:200, data:{history:[]}},请将下方res.history替换为对应路径如res.data.history,这是嵌套结构场景下最高发的错误点
if (!Array.isArray(res.history)) return console.error('history字段不存在或不是数组,当前返回结构:', res); formatToTable(res.history); } catch (err) { console.error('JSON解析失败:', err); } } xhr.send();
jQuery简化实现
function formatToTable(historyData) { const renderData = historyData.slice(0, 5); const $tbody = $('#draws_table tbody').empty(); $.each(renderData, function(_, singleDraw) { const [date, time, numberArr] = singleDraw; const $tr = $('<tr>'); $.each([date, time, ...numberArr], function(_, val) { $tr.append($('<td>').text(val)); }); $tbody.append($tr); }); } $.getJSON('draws.json', function(res) { if (Array.isArray(res.history)) formatToTable(res.history); })
快速调试技巧
- 先在请求成功回调里打印完整返回的JSON结构,确认
history数组的取值路径100%正确,嵌套结构场景下80%的渲染失败都是路径写错导致 - 打印解构后的
numberArr字段,确认其长度为20,展开后行总列数为22,和表头列数完全匹配 - 所有DOM渲染逻辑必须放在请求成功的回调内部执行,不要提前调用渲染方法
内容的提问来源于stack exchange,提问作者YoYoYo
相关产品推荐
相关产品推荐

