
本文讲解如何通过 javascript 动态拼接 html 字符串,在 sweetalert 弹窗中渲染由 ajax 返回的可变长度数据表格,无需模板引擎,纯原生 js + 字符串模板实现。
在 Web 开发中,常需将异步获取的数据(如数据库查询结果)以表格形式展示在模态框中。SweetAlert 是轻量且美观的弹窗库,但其 html 选项仅接受字符串,不支持直接嵌入循环逻辑——这意味着你不能在模板字符串中写 for 语句。解决方案是:先在 JS 中生成完整的 以下为推荐实现方式(已优化健壮性与可读性): ✅ 关键要点说明: 该方案简洁高效,完全满足“AJAX → JSON → 动态表格 → SweetAlert 展示”的典型流程,无需引入额外依赖,适合快速集成与维护。 行字符串数组,再用 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;
}
// 安全处理空数据
if (!Array.isArray(data) || data.length === 0) {
Swal.fire({
html: `<p><h5>${custId}</h5></p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/ai/1009" title="人声去除"><img
src="https://img.php.cn/upload/ai_manual/001/503/042/68b6cdd500098735.jpeg" alt="人声去除" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/ai/1009" title="人声去除">人声去除</a>
<p>用强大的AI算法将声音从音乐中分离出来</p>
</div>
<a href="/ai/1009" title="人声去除" 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>
${startDate} ${endDate}<br>
<p class="text-muted">暂无匹配记录</p>`
});
return;
}
// 使用 map 构建所有 <tr> 字符串(自动处理转义风险较低的字段)
const rows = data.map(row =>
`<tr>
<td>${row.item || ''}</td>
<td>${row.count || '0'}</td>
</tr>`
).join('');
Swal.fire({
html: `
<p><h5>${custId}</h5></p><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>
${startDate} ${endDate}
<br><br>
<table class="table-datatable display responsive nowrap table-bordered table-striped">
<tbody>
${rows}
</tbody>
</table>
`,
customClass: {
popup: 'swal2-popup--table'
},
showCloseButton: true,
focusConfirm: false
});
},
error: function(xhr) {
Swal.fire("请求失败", `HTTP ${xhr.status}: ${xhr.statusText}`, "error");
}
});










