如何通过Ajax将分组数组渲染为指定格式的表格?
解决方案
步骤1:调整数据处理逻辑
要实现目标表格,需要先把日期分组的原始数据转换为以员工ID为核心的结构,同时补全日期范围内的所有缺失日期(比如2023-10-02),保证表头和单元格一一对应。
步骤2:替换Ajax回调代码
把你现有代码中的success函数替换为以下逻辑,完整代码如下:
$.ajax({ type: "get", url: "{{ route('schedules.fetch-table-schedule') }}", dataType: "json", success: function (response) { const groupedData = response.result; // 1. 生成完整连续日期列表(补全缺失日期) const sortedDates = Object.keys(groupedData).sort(); const start = new Date(sortedDates[0]); const end = new Date(sortedDates[sortedDates.length - 1]); const fullDateList = []; for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) { fullDateList.push(d.toISOString().split('T')[0]); } // 2. 构建员工-日期排班映射表 const employeeScheduleMap = {}; fullDateList.forEach(date => { const dailyEmployees = groupedData[date] || []; dailyEmployees.forEach(emp => { if (!employeeScheduleMap[emp.emp_id]) { employeeScheduleMap[emp.emp_id] = { name: emp.name, codes: {} }; } employeeScheduleMap[emp.emp_id].codes[date] = emp.code; }); }); // 3. 渲染表头 const tableHead = $("#schedule-table thead"); tableHead.empty(); let headerHtml = "<tr><th>ID</th>"; fullDateList.forEach(date => { headerHtml += `<th>${date}</th>`; }); headerHtml += "</tr>"; tableHead.append(headerHtml); // 4. 渲染表体 const tableBody = $("#schedule-table #body_schedule"); tableBody.empty(); Object.keys(employeeScheduleMap).sort().forEach(empId => { const empData = employeeScheduleMap[empId]; let rowHtml = `<tr><td>${empId}</td>`; fullDateList.forEach(date => { const code = empData.codes[date] || ""; rowHtml += `<td>${code}</td>`; }); rowHtml += "</tr>"; tableBody.append(rowHtml); }); } });
关键逻辑说明
- 补全日期:通过循环遍历起始到结束日期,生成连续日期列表,解决原始数据中缺失日期的表头显示问题。
- 员工映射表:将每个员工的各日期排班code统一存储,后续可快速匹配日期填充单元格。
- 渲染流程:先清空原有表头和表体,再分别生成表头行和员工数据行,无排班的日期自动填充空单元格。
配套HTML结构
确保页面中存在对应的表格容器:
<div class="s-table-container"> <table class="s-table" id="schedule-table"> <thead></thead> <tbody id="body_schedule"></tbody> </table> </div>
内容的提问来源于stack exchange,提问作者Choky
相关产品推荐
相关产品推荐

