使用Ajax Get方法前端获取MongoDB数据的硬编码逻辑优化求助
解决方案
1. 调整HTML结构
删除原有写死的所有数据行<tr>,仅保留表头,新增带唯一id的tbody容器用于动态插入内容,修改后的代码如下:
<table class="table2"> <thead> <tr> <th style="text-align:center">SL.No</th> <th style="text-align:center">Purchaser Name</th> <th style="text-align:center">Email</th> <th style="text-align:center">Address</th> <th style="text-align:center">Phone No</th> <th style="text-align:center">Status</th> </tr> </thead> <tbody id="purchaserListBody"> <!-- 动态生成的行都会插入到这里 --> </tbody> </table>
2. 替换AJAX硬编码渲染逻辑
将success回调中固定下标的赋值逻辑替换为数组遍历动态生成行的逻辑,完整代码如下:
$.ajax({ dataType: "json", url: "/purchaser/purchasersList", type: "GET", global: false, // 提示:同步请求async:false会阻塞页面渲染,无特殊需求建议删掉这行用默认异步 async: false, success: function(response) { console.log("response is:", response); // 先清空容器,避免重复渲染 const tbody = $('#purchaserListBody'); tbody.empty(); // 遍历返回的数组,逐个生成行 response.forEach((item, index) => { const rowHtml = ` <tr> <td height="50">${index + 1}</td> <td height="50">${item.userName}</td> <td height="50">${item.email_id}</td> <td height="50">${item.address}</td> <td height="50">${item.phoneNumber}</td> <td height="50">Active</td> </tr> `; tbody.append(rowHtml); }); }, error: function (jqXHR, textStatus, errorThrown) { console.log("Error Response jqXHR is:" + jqXHR); } });
修改后逻辑会自动适配返回的数据条数,无论返回多少条数据都可以自动生成对应行数,无需手动新增元素id和赋值代码。
内容的提问来源于stack exchange,提问作者Shining
相关产品推荐
相关产品推荐

