JavaScript 在 HTML 中显示 JSON 数据的完整指南
在 Web 开发中,经常需要将后端返回的 JSON 数据在前端 HTML 页面中进行展示,JavaScript 作为连接前后端的核心语言,提供了多种方法来实现这一需求,本文将详细介绍几种常用的方法,帮助您轻松地将 JSON 数据呈现在 HTML 页面上。
使用 innerHTML 直接插入(简单但需注意安全)
最直接的方法是使用 JavaScript 的 innerHTML 属性,将 JSON 数据转换为字符串后插入到 HTML 元素中。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">JSON 数据显示示例</title>
</head>
<body>
<h1>用户信息</h1>
<div id="jsonDisplay"></div>
<script>
// 示例 JSON 数据
const userData = {
"name": "张三",
"age": 30,
"email": "zhangsan@example.com",
"hobbies": ["阅读", "旅行", "摄影"]
};
// 将 JSON 对象转换为格式化的字符串
const jsonString = JSON.stringify(userData, null, 2);
// 插入到 HTML 元素中
document.getElementById('jsonDisplay').innerHTML = `<pre>${jsonString}</pre>`;
</script>
</body>
</html>
说明:
JSON.stringify()方法将 JavaScript 对象转换为 JSON 字符串- 第二个参数
null表示不进行过滤 - 第三个参数
2表示缩进空格数,使 JSON 字符串格式化更易读 - 使用
<pre>标签可以保留 JSON 字符串的格式
注意:直接使用 innerHTML 插入用户提供的 JSON 数据可能存在 XSS 安全风险,如果数据来自不可信的源,应先进行转义处理。
动态创建 HTML 元素(更灵活)
如果需要将 JSON 数据中的各个字段分别展示,可以动态创建 HTML 元素。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">动态 JSON 显示示例</title>
<style>
.user-card {
border: 1px solid #ccc;
border-radius: 5px;
padding: 15px;
margin: 10px;
max-width: 400px;
}
.user-card h2 {
margin-top: 0;
}
.user-card p {
margin: 5px 0;
}
.hobby {
display: inline-block;
background: #f0f0f0;
padding: 3px 8px;
margin: 2px;
border-radius: 3px;
}
</style>
</head>
<body>
<h1>用户列表</h1>
<div id="userList"></div>
<script>
// 示例 JSON 数据
const usersData = [
{
"id": 1,
"name": "李四",
"age": 28,
"email": "lisi@example.com",
"hobbies": ["编程", "音乐", "健身"]
},
{
"id": 2,
"name": "王五",
"age": 35,
"email": "wangwu@example.com",
"hobbies": ["绘画", "烹饪", "园艺"]
}
];
const userList = document.getElementById('userList');
usersData.forEach(user => {
// 创建用户卡片容器
const userCard = document.createElement('div');
userCard.className = 'user-card';
// 添加姓名
const nameElement = document.createElement('h2');
nameElement.textContent = user.name;
userCard.appendChild(nameElement);
// 添加年龄
const ageElement = document.createElement('p');
ageElement.textContent = `年龄: ${user.age}`;
userCard.appendChild(ageElement);
// 添加邮箱
const emailElement = document.createElement('p');
emailElement.textContent = `邮箱: ${user.email}`;
userCard.appendChild(emailElement);
// 添加爱好
const hobbiesElement = document.createElement('p');
hobbiesElement.textContent = '爱好: ';
user.hobbies.forEach(hobby => {
const hobbySpan = document.createElement('span');
hobbySpan.className = 'hobby';
hobbySpan.textContent = hobby;
hobbiesElement.appendChild(hobbySpan);
});
userCard.appendChild(hobbiesElement);
// 将用户卡片添加到列表中
userList.appendChild(userCard);
});
</script>
</body>
</html>
说明:
- 这种方法可以完全控制 JSON 数据的展示方式
- 可以添加 CSS 样式使展示更美观
- 适合结构复杂或需要定制化展示的 JSON 数据
使用模板字符串(现代简洁)
ES6 的模板字符串使得在 HTML 中嵌入数据变得更加简洁。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">模板字符串 JSON 显示示例</title>
<style>
.product {
border: 1px solid #ddd;
border-radius: 8px;
padding: 15px;
margin: 15px 0;
background-color: #f9f9f9;
}
.product h3 {
color: #333;
margin-top: 0;
}
.product .price {
color: #e44d26;
font-weight: bold;
}
.product .description {
color: #666;
margin: 10px 0;
}
</style>
</head>
<body>
<h1>商品列表</h1>
<div id="productList"></div>
<script>
// 示例 JSON 数据
const productsData = [
{
"id": 101,
"name": "智能手机",
"price": 2999,
"description": "高性能智能手机,配备先进的摄像头和长续航电池",
"features": ["6.7英寸OLED屏幕", "128GB存储", "5G网络"]
},
{
"id": 102,
"name": "无线耳机",
"price": 599,
"description": "主动降噪无线耳机,提供卓越的音质体验",
"features": ["主动降噪", "30小时续航", "快速充电"]
}
];
const productList = document.getElementById('productList');
// 使用模板字符串生成 HTML
const productsHTML = productsData.map(product => `
<div class="product">
<h3>${product.name}</h3>
<p class="price">¥${product.price}</p>
<p class="description">${product.description}</p>
<p>特点: ${product.features.join(' • ')}</p>
</div>
`).join('');
productList.innerHTML = productsHTML;
</script>
</body>
</html>
说明:
- 模板字符串(反引号包围)可以方便地嵌入变量
map()方法遍历数组并生成 HTML 字符串join('')将数组元素合并为单个字符串- 代码更简洁,可读性更强
使用 fetch API 从服务器获取 JSON 数据
在实际应用中,JSON 数据通常来自服务器,可以使用 fetch API 获取数据并显示。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">从服务器获取 JSON 数据示例</title>
<style>
.loading {
color: #666;
}
.error {
color: #e44d26;
}
.post {
border: 1px solid #ddd;
border-radius: 5px;
padding: 10px;
margin: 10px 0;
}
.post h3 {
margin-top: 0;
}
</style>
</head>
<body>
<h1>博客文章</h1>
<div id="postsContainer">
<p class="loading">加载中...</p>
</div>
<script>
const postsContainer = document.getElementById('postsContainer');
// 使用 fetch API 从 JSONPlaceholder 获取示例数据
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json();
})
.then(posts => {
// 清除加载提示
postsContainer.innerHTML = '';
// 显示前5篇文章
const postsToShow = posts.slice(0, 5);
postsToShow.forEach(post => {
const postElement = document.createElement('div');
postElement.className = 'post';
postElement.innerHTML = `
<h3>${post.title}</h3>
<p>${post.body}</p>
`;
postsContainer.appendChild(postElement);
});
})
.catch(error => {
postsContainer.innerHTML = `<p class="error">加载失败: ${error.message}</p>`;


还没有评论,来说两句吧...