如何在验证成功条件内遍历JSON生成HTML保龄球分数表格?
保龄球分数表格生成问题解决办法
第一步:确认AJAX请求状态与返回数据
先在AJAX的success回调里打印返回数据,确认请求确实拿到了正确格式的JSON:
$.ajax({ url: "/your-api-url", // 替换成你的实际接口地址 type: "GET", // 或POST,匹配后端接口定义 dataType: "json", // 明确指定接收JSON格式 success: function(res) { // 先打印数据,检查结构是否符合预期 console.log("返回数据:", res); // 后续表格生成逻辑写在这里 }, error: function(xhr, status, error) { // 捕获请求失败的情况,快速排查问题 console.error("请求失败:", status, error); console.error("响应内容:", xhr.responseText); } });
同时检查后端Controller返回的JSON是否为数组格式(因为要遍历多条分数记录),正确的返回格式示例:
[ {"playerName": "张三", "frame1": 10, "frame2": 8, "totalScore": 18}, {"playerName": "李四", "frame1": 7, "frame2": 3, "totalScore": 17} ]
第二步:修正DOM元素选择与表格生成逻辑
确保你要插入表格的容器元素存在,并且选择器正确。比如在View中定义容器:
<div id="bowlingScoreTable"></div>
然后修改JS中的表格生成代码,注意完整的表格结构(表头+表体),用ES6模板字符串避免引号嵌套错误:
success: function(res) { // 先判断返回数据是否为有效数组 if (!Array.isArray(res) || res.length === 0) { $("#bowlingScoreTable").html("<p>暂无分数记录</p>"); return; } // 拼接表格HTML let tableHtml = ` <table border="1" cellpadding="8" cellspacing="0"> <thead> <tr> <th>玩家姓名</th> <th>第一局分数</th> <th>第二局分数</th> <th>总分</th> </tr> </thead> <tbody> `; // 遍历JSON数组生成表体行 res.forEach(score => { tableHtml += ` <tr> <td>${score.playerName || "-"}</td> <td>${score.frame1 || 0}</td> <td>${score.frame2 || 0}</td> <td>${score.totalScore || 0}</td> </tr> `; }); tableHtml += ` </tbody> </table> `; // 将生成的表格插入到容器中 $("#bowlingScoreTable").html(tableHtml); }
第三步:排查常见坑点
- jQuery未引入:如果使用
$.ajax,确保View里已经引入jQuery库:<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> - 字段名不匹配:JS中使用的字段名(如
playerName、frame1)必须与后端返回的JSON字段完全一致(大小写敏感)。 - 跨域问题:如果前后端部署在不同域名下,需要后端配置CORS允许跨域请求。
- 容器选择错误:检查
$("#bowlingScoreTable")中的ID是否与View里的容器ID完全一致。
内容的提问来源于stack exchange,提问作者Nipuna Kusal
相关产品推荐
相关产品推荐

