如何使用Ajax请求JSON数据并实现回显
在现代Web开发中,Ajax(Asynchronous JavaScript and XML)技术是实现页面异步数据交互的核心,本文将详细介绍如何使用Ajax请求JSON数据,并将获取到的数据回显到页面上,帮助开发者这一常用技能。
Ajax请求JSON数据的基本流程
使用Ajax请求JSON数据并回显通常包含以下几个步骤:
- 创建XMLHttpRequest对象或使用Fetch API
- 配置请求参数(URL、方法、数据等)
- 发送请求
- 处理响应数据
- 将数据解析并回显到页面
使用XMLHttpRequest实现Ajax请求
以下是使用传统的XMLHttpRequest对象实现Ajax请求JSON数据并回显的完整代码示例:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">Ajax请求JSON数据回显示例</title>
<style>
body {
font-family: 'Arial', sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
line-height: 1.6;
}
h1 {
color: #333;
text-align: center;
}
button {
background-color: #4CAF50;
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
button:hover {
background-color: #45a049;
}
#result {
margin-top: 20px;
padding: 15px;
border: 1px solid #ddd;
border-radius: 4px;
background-color: #f9f9f9;
}
.loading {
color: #666;
font-style: italic;
}
.error {
color: #d9534f;
font-weight: bold;
}
.user-card {
border: 1px solid #ddd;
border-radius: 8px;
padding: 15px;
margin-bottom: 15px;
background-color: white;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.user-card h3 {
margin-top: 0;
color: #333;
}
.user-card p {
margin: 5px 0;
}
</style>
</head>
<body>
<h1>Ajax请求JSON数据回显示例</h1>
<button id="fetchData">获取用户数据</button>
<div id="result">
<p class="loading">点击按钮获取数据...</p>
</div>
<script>
document.getElementById('fetchData').addEventListener('click', function() {
// 1. 创建XMLHttpRequest对象
var xhr = new XMLHttpRequest();
// 2. 配置请求参数
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users', true);
// 3. 设置响应类型为JSON
xhr.responseType = 'json';
// 4. 设置加载中提示
var resultDiv = document.getElementById('result');
resultDiv.innerHTML = '<p class="loading">数据加载中,请稍候...</p>';
// 5. 设置请求完成后的回调函数
xhr.onload = function() {
if (xhr.status === 200) {
// 请求成功,处理响应数据
var users = xhr.response;
displayUsers(users);
} else {
// 请求失败
resultDiv.innerHTML = '<p class="error">请求失败,状态码:' + xhr.status + '</p>';
}
};
// 6. 设置请求错误时的回调函数
xhr.onerror = function() {
resultDiv.innerHTML = '<p class="error">请求发生错误,请检查网络连接</p>';
};
// 7. 发送请求
xhr.send();
});
// 回显用户数据到页面的函数
function displayUsers(users) {
var resultDiv = document.getElementById('result');
resultDiv.innerHTML = ''; // 清空之前的内容
if (users && users.length > 0) {
users.forEach(function(user) {
var userCard = document.createElement('div');
userCard.className = 'user-card';
userCard.innerHTML = `
<h3>${user.name}</h3>
<p><strong>用户名:</strong> ${user.username}</p>
<p><strong>邮箱:</strong> ${user.email}</p>
<p><strong>电话:</strong> ${user.phone}</p>
<p><strong>网站:</strong> ${user.website}</p>
<p><strong>地址:</strong> ${user.address.street}, ${user.address.city}</p>
`;
resultDiv.appendChild(userCard);
});
} else {
resultDiv.innerHTML = '<p>没有获取到用户数据</p>';
}
}
</script>
</body>
</html>
使用Fetch API实现Ajax请求
现代Web开发中,更推荐使用Fetch API,它提供了更简洁的语法和Promise支持,以下是使用Fetch API的实现:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">使用Fetch API请求JSON数据回显</title>
<style>
body {
font-family: 'Arial', sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
line-height: 1.6;
}
h1 {
color: #333;
text-align: center;
}
button {
background-color: #007bff;
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
button:hover {
background-color: #0069d9;
}
#result {
margin-top: 20px;
padding: 15px;
border: 1px solid #ddd;
border-radius: 4px;
background-color: #f9f9f9;
}
.loading {
color: #666;
font-style: italic;
}
.error {
color: #d9534f;
font-weight: bold;
}
.product-card {
border: 1px solid #ddd;
border-radius: 8px;
padding: 15px;
margin-bottom: 15px;
background-color: white;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
display: flex;
}
.product-info {
flex: 1;
}
.product-image {
width: 100px;
height: 100px;
object-fit: cover;
border-radius: 4px;
margin-left: 15px;
}
.product-card h3 {
margin-top: 0;
color: #333;
}
.product-card p {
margin: 5px 0;
}
.price {
font-weight: bold;
color: #28a745;
font-size: 18px;
}
</style>
</head>
<body>
<h1>使用Fetch API请求JSON数据回显</h1>
<button id="fetchProducts">获取产品数据</button>
<div id="result">
<p class="loading">点击按钮获取数据...</p>
</div>
<script>
document.getElementById('fetchProducts').addEventListener('click', function() {
// 显示加载中提示
var resultDiv = document.getElementById('result');
resultDiv.innerHTML = '<p class="loading">数据加载中,请稍候...</p>';
// 使用Fetch API发送请求
fetch('https://fakestoreapi.com/products')
.then(response => {
// 检查响应状态
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json(); // 解析JSON数据
})
.then(products => {
// 数据获取成功,回显到页面
displayProducts(products);
})
.catch(error => {
// 处理错误
resultDiv.innerHTML = '<p class="error">请求失败: ' + error.message + '</p>';
});
});
// 回显产品数据到页面的函数
function displayProducts(products) {
var resultDiv = document.getElementById('result');
resultDiv.innerHTML = ''; // 清空之前的内容
if (products && products.length > 0) {
products.forEach(function(product) {
var productCard = document.createElement('div');
productCard.className = 'product-card';
productCard.innerHTML = `


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