Skip to content

JSON 示例

本示例演示了如何从一个简单的 API(应用编程接口)端点(这里使用 PHP 和 MySQL 模拟)获取 JSON 数据,并使用现代 JavaScript 将其显示在网页上。

现代客户端 JavaScript(使用 Fetch API)

Section titled “现代客户端 JavaScript(使用 Fetch API)”

以下是在浏览器中运行的 HTML 和 JavaScript 代码。它使用 fetch API 请求数据,并动态创建表格行来显示数据。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Customer Data</title>
<style>
table, th, td {
border: 1px solid #ccc;
border-collapse: collapse;
padding: 8px;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h1>Customer List</h1>
<table id="customerTable">
<thead>
<tr>
<th>Name</th>
<th>City</th>
<th>Country</th>
</tr>
</thead>
<tbody id="customerTableBody">
<!-- Data will be inserted here -->
</tbody>
</table>
<p id="loadingStatus">Loading data...</p>
<p id="errorStatus" style="color: red;"></p>
<script>
// 定义 API 端点 URL
// 替换为你实际的 API 端点
const apiUrl = 'https://your-api-endpoint.example.com/customers'; // 示例 URL
// 或者用于测试的本地 PHP 文件
// const apiUrl = 'customers_api.php';
const tableBody = document.getElementById('customerTableBody');
const loadingStatus = document.getElementById('loadingStatus');
const errorStatus = document.getElementById('errorStatus');
// 使用 async/await 让异步代码更简洁
async function fetchCustomers() {
try {
const response = await fetch(apiUrl);
// 检查请求是否成功
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
// 解析 JSON 响应
const customers = await response.json();
// 清除加载状态
loadingStatus.textContent = '';
// 填充表格
populateTable(customers);
} catch (error) {
// 处理错误(网络问题、解析错误等)
console.error('Error fetching customer data:', error);
loadingStatus.textContent = '';
errorStatus.textContent = `Failed to load data: ${error.message}`;
}
}
function populateTable(customers) {
// 清除之前的数据(可选)
tableBody.innerHTML = '';
if (!Array.isArray(customers)) {
console.error('期望获取客户数组,但收到了:', customers);
errorStatus.textContent = 'Received invalid data format from server.';
return;
}
// 为每个客户创建表格行
customers.forEach(customer => {
const row = tableBody.insertRow();
const nameCell = row.insertCell();
// 假设 JSON 键是 'Name', 'City', 'Country'
nameCell.textContent = customer.Name;
const cityCell = row.insertCell();
cityCell.textContent = customer.City;
const countryCell = row.insertCell();
countryCell.textContent = customer.Country;
});
}
// 页面加载时调用函数来获取和显示数据
fetchCustomers();
</script>
</body>
</html>

这个 PHP 脚本连接到 MySQL 数据库,检索客户数据,并使用内置的 json_encode() 函数将其编码为 JSON。这比手动构造 JSON 字符串更安全可靠。

<?php
// 设置 CORS(跨域资源共享,如果需要)头部和 JSON 内容类型
header("Access-Control-Allow-Origin: *"); // 生产环境中需调整以确保安全
header("Content-Type: application/json; charset=UTF-8");
// 数据库配置(替换为你的凭据)
$serverName = "your_db_server";
$userName = "your_db_user";
$password = "your_db_password";
$dbName = "your_database_name"; // e.g., "Northwind"
// 创建连接
$conn = new mysqli($serverName, $userName, $password, $dbName);
// 检查连接
if ($conn->connect_error) {
// 以 JSON 格式发送错误响应
http_response_code(500); // 内部服务器错误
echo json_encode(["error" => "Connection failed: " . $conn->connect_error]);
// 停止脚本执行
exit();
}
// 用于获取数据的 SQL 查询
// 使用特定的列名是一个好习惯
// 添加 LIMIT 限制以确保安全
$sql = "SELECT CompanyName, City, Country FROM Customers LIMIT 50";
$result = $conn->query($sql);
// 初始化一个空数组
$customers = [];
if ($result && $result->num_rows > 0) {
// 将所有结果提取到关联数组中
// 重命名键以保持一致性(可选,但通常更受欢迎)
while ($row = $result->fetch_assoc()) {
$customers[] = [
'Name' => $row['CompanyName'],
'City' => $row['City'],
'Country' => $row['Country']
];
}
} else if (!$result) {
// 处理 SQL 查询错误
http_response_code(500);
echo json_encode(["error" => "Query failed: " . $conn->error]);
$conn->close();
exit();
}
// 注意:如果 $result->num_rows 为 0,将返回一个空数组 [],这是有效的 JSON。
// 关闭数据库连接
$conn->close();
// 将数组编码为 JSON 并输出
// json_encode 处理特殊字符并确保 JSON 格式有效
echo json_encode($customers);
?>
  • **客户端:**使用带有 async/await 的 fetch API 处理现代异步请求。
  • **客户端:**包含基本的错误处理(try...catch,response.ok)。
  • **客户端:**动态创建 DOM(文档对象模型)元素,而不是使用 innerHTML 处理大型字符串(对于复杂结构更安全,通常性能更好)。
  • **服务器:**使用 json_encode() 进行可靠的 JSON 生成。
  • **服务器:**包含基本的数据库连接错误处理。
  • **服务器:**设置正确的 Content-Type: application/json 头部。
  • **服务器:**清晰地组织输出数据结构。

**注意:**此 PHP 示例假设使用 MySQL 数据库。在现代 Web 开发中,你可能会使用各种后端语言(Node.js、Python、Ruby、Java、C#)和数据库(PostgreSQL、MongoDB 等)。核心概念保持不变:获取数据并将其序列化为 JSON。