<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JSON 數據動態加載演示</title>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
</head>
<body>
<button id="loadBtn">加載數據</button>
<table id="infoTable" border="1">
<thead>
<tr id="title">
<th>姓名</th><th>性別</th><th>地址</th><th>主頁</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
$(function() {
$('#loadBtn').on('click', function() {
$.getJSON('info.json', function(data) {
var html = '';
$.each(data, function(i, item) {
html += '<tr>'
+ '<td>' + item.name + '</td>'
+ '<td>' + item.sex + '</td>'
+ '<td>' + item.address + '</td>'
+ '<td><a href="' + item.home + '" target="_blank">鏈接</a></td>'
+ '</tr>';
});
$('#infoTable tbody').html(html);
}).fail(function(jqXHR, textStatus) {
alert('加載失敗:' + textStatus);
});
});
});
</script>
</body>
</html>
[
{ "name": "張三", "sex": "男", "address": "杭州", "home": "https://www.zhangsan.com" },
{ "name": "李四", "sex": "女", "address": "北京", "home": "https://www.lisi.com" }
]
$.getJSON(GET 請求)或配置服務器支持 POST。file:// 協議,AJAX 會被瀏覽器攔截。需啟動本地服務器(如 npx serve、VS Code Live Server)。定期從數據庫導出靜態 JSON,前端直接讀取,減輕數據庫壓力,適合「數據更新頻率低、讀取頻率高」的公開頁面。