接口通常返回 JSON。前端拿到数据后,需要把数组或对象转换成用户能看懂的界面。渲染时既要结构清晰,也要防止把不可信内容当成 HTML 执行。

本节要点

  • JSON.parse 把字符串转成对象,JSON.stringify 把对象转成字符串。
  • 数组可以用 map 生成 HTML 片段,再用 join 拼接。
  • 接口数据可能包含用户输入,直接拼 innerHTML 存在 XSS 风险。
  • 优先用 textContent 写入文本,必须插入 HTML 时先做转义。

可运行示例

下面的示例把教程数组渲染成卡片,并对文本做转义。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>JSON 渲染</title>
  <style>
    .card { border: 1px solid #ddd; border-radius: 8px; padding: 12px; margin: 10px 0; }
    .level { color: #0a7d5a; font-size: 12px; }
  </style>
</head>
<body>
  <h1>教程列表</h1>
  <div id="cards">加载中…</div>

  <script>
    function escapeHtml(value) {
      return String(value)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
    }

    fetch('/ajax/demo/data.json')
      .then(response => response.json())
      .then(data => {
        const html = data.map(item => `
          <article class="card">
            <span class="level">${escapeHtml(item.level)}</span>
            <h2>${escapeHtml(item.title)}</h2>
            <p>${escapeHtml(item.desc)}</p>
          </article>
        `).join('');
        document.getElementById('cards').innerHTML = html;
      })
      .catch(error => {
        document.getElementById('cards').textContent = '加载失败:' + error.message;
      });
  </script>
</body>
</html>
运行说明:打开页面即可看到卡片列表。把 data.json 中某条 title 改成带