
本文讲解如何在 javascript 中基于 ajax 返回的动态数组,安全高效地构建 html 表格字符串,并嵌入 sweetalert 弹窗中,避免语法错误,支持任意长度数据。
在前端开发中,常需将异步获取的 JSON 数据(如数据库查询结果)渲染为 HTML 表格,并展示在模态弹窗(如 SweetAlert)中。但直接在 Swal.fire({ html: '...' }) 的模板字符串内写循环语句(如 for)会导致语法错误——因为模板字符串中不支持执行语句,只支持表达式插值。
✅ 正确做法是:先在 success 回调中预处理数据,生成完整的 以下为推荐实现(已优化安全性与可读性): ? 关键要点总结: 该方案简洁、健壮、可维护,适用于任意两列(或多列)结构的动态表格场景。
字符串数组,再用 .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><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/xiazai/code/11113" title="云网OA"><img
src="https://img.php.cn/upload/webcode/000/000/001/176500620968446.jpg" alt="云网OA" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/xiazai/code/11113" title="云网OA">云网OA</a>
<p>采用JSP开发的办公自动化产品、基于B/S结构,运行环境:JDK v1.5、Tomcat v5.5、MySQL v4.1,三者均为以上版本其他相关内容:可视化流程设计: 流程支持串签、会签和分支流程,可以设置流程节点的修改、删除权限,并可指定流程中各个用户在表单中可以填写的域。智能表单所见即所得设计: 智能设计,自动在数据库中生成表格,方便优化程序 公共交流: 集论坛、博客、聊天室于一体文件柜:C</p>
</div>
<a href="/xiazai/code/11113" title="云网OA" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/cb6835dc7db1" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">前端免费学习笔记(深入)</a>”;</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, "'");
}
,提升用户体验;lspan="2">暂无数据










