如何将AJAX返回的用户名与高分数据追加到HTML表格中
实现方案
- 首先将接口返回的嵌套对象转换为数组,提取每个uid对应的用户数据
- 对数组按Highscore字段降序排序,注意将字符串类型的Highscore统一转换为数字类型避免排序错误
- 遍历排序后的数组,拼接表格行HTML插入到目标表格中
常见失败原因:返回结果是嵌套对象结构,直接遍历会拿到uid键名和对应的值两层结构,需要先提取所有值组成数组再遍历。
jQuery 实现方案(适配你提到的each循环写法)
$(function() { // 页面加载完成后触发AJAX请求 $.ajax({ url: '替换为你的实际接口地址', type: 'GET', dataType: 'json', success: function(res) { // 1. 提取所有用户数据为数组,过滤掉uid字段 const scoreList = Object.values(res); // 2. 按高分降序排序,统一转数字处理字符串类型的Highscore scoreList.sort((a, b) => Number(b.Highscore) - Number(a.Highscore)); // 3. 遍历生成表格行 let htmlStr = ''; $.each(scoreList, function(index, item) { // 排名从1开始,如需同分数同排名可调整规则 const rank = index + 1; htmlStr += `<tr> <td style="text-align: center;">${rank}</td> <td style="text-align: center;">${item.username}</td> <td style="text-align: center;">${item.Highscore}</td> </tr>`; }); // 插入到表格中,保留原有表头 $('#records_table').append(htmlStr); }, error: function(err) { console.log('数据请求失败', err); } }) })
原生JS实现方案(无需引入jQuery)
document.addEventListener('DOMContentLoaded', function() { fetch('替换为你的实际接口地址') .then(res => res.json()) .then(data => { const scoreList = Object.values(data); scoreList.sort((a, b) => Number(b.Highscore) - Number(a.Highscore)); const table = document.getElementById('records_table'); scoreList.forEach((item, index) => { const row = table.insertRow(); const rankCell = row.insertCell(0); const userCell = row.insertCell(1); const scoreCell = row.insertCell(2); rankCell.style.textAlign = 'center'; userCell.style.textAlign = 'center'; scoreCell.style.textAlign = 'center'; rankCell.textContent = index + 1; userCell.textContent = item.username; scoreCell.textContent = item.Highscore; }) }) .catch(err => console.log('数据请求失败', err)) })
内容的提问来源于stack exchange,提问作者Xerxes
相关产品推荐
相关产品推荐

