
本文讲解如何在 javascript 中基于 ajax 返回的动态数组,安全高效地构建 html 表格字符串,并嵌入 sweetalert 弹窗中,避免语法错误,支持任意长度数据。
在前端开发中,常需将异步获取的 JSON 数据(如数据库查询结果)渲染为 HTML 表格,并展示在模态弹窗(如 SweetAlert)中。但直接在 Swal.fire({ html: '...' }) 的模板字符串内写循环语句(如 for)会导致语法错误——因为模板字符串中不支持执行语句,只支持表达式插值。
✅ 正确做法是:先在 success 回调中预处理数据,生成完整的 zuojiankuohaophpcntr> 字符串数组,再用 .join('') 拼接后注入 HTML 模板。
以下为推荐实现(已优化安全性与可读性):
$.ajax({
url: "../model/test.php",
data: {
'order-startDate': startDate,
'order-endDate': endDate,
'order-custId': custId
},
type: 'GET',
success: function(result) {
let data;
try {
data = JSON.parse(result);
} catch (e) {
console.error("JSON 解析失败:", e);
Swal.fire("错误", "服务器返回数据格式异常", "error");
return;
}
// ✅ 使用 map 构建每行 HTML,自动处理空数组情况
const tableRows = data.length > 0
? data.map(item =>
`<tr>
<td>${escapeHtml(item.item || '')}</td>
<td>${escapeHtml(item.count || '')}</td>
</tr>`
).join('')
: '<tr><td colspan="2" class="text-center text-muted">暂无数据</td></tr>';
// 渲染 SweetAlert 弹窗
Swal.fire({
html: `
<p><h5>${escapeHtml(custId)}</h5></p>
<br>
${escapeHtml(startDate)} ${escapeHtml(endDate)}
<br>
<table class="table-datatable display responsive nowrap table-bordered table-striped">
<tbody>${tableRows}</tbody>
</table>
`,
customClass: {
popup: 'swal2-popup-lg' // 可选:适配宽表
},
width: '800px'
});
},
error: function(xhr) {
Swal.fire("请求失败", `HTTP ${xhr.status}: ${xhr.statusText}`, "error");
}
});
// ? 辅助函数:防止 XSS,对用户数据做基础 HTML 转义
function escapeHtml(unsafe) {
if (typeof unsafe !== 'string') return '';
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}? 关键要点总结:
立即学习“前端免费学习笔记(深入)”;
- ❌ 禁止在模板字符串中写 for、if 等语句;✅ 改用 map() + join() 预生成 HTML 片段;
- ⚠️ 始终对 JSON.parse() 加 try...catch,避免解析失败导致脚本中断;
- ?️ 对所有来自服务端的字段(如 item、count、custId)使用 escapeHtml() 转义,防范 XSS;
- ? 若数据为空,主动渲染 <tr><td colspan="2">暂无数据</td></tr>,提升用户体验;
- ? SweetAlert 支持 width 和 customClass,便于响应式表格布局。
该方案简洁、健壮、可维护,适用于任意两列(或多列)结构的动态表格场景。











