在現代 Web 開發中,JSON(JavaScript Object Notation)已成為前後端資料交換的標準格式。無論是 AJAX 請求、API 介接,還是前端框架(Vue、React、jQuery)與後端溝通,JSON 都是首選。本文將詳細說明 PHP 如何正確輸出 JSON 格式資料,並搭配 jQuery 進行前端解析與渲染。
jQuery 提供 $.getJSON() 方法,可自動發送 GET 請求並將回應解析為 JavaScript 物件/陣列。
<script>
$(function() {
$('#send').click(function() {
$.getJSON('test.json', function(data) {
$('#resText').empty();
var html = '';
$.each(data, function(index, comment) {
html += '<div class="comment"><h6>' + comment['username'] + ':</h6><p class="para">' + comment['content'] + '</p></div>';
});
$('#resText').html(html);
});
});
});
</script>
[
{ "username": "張三", "content": "沙發." },
{ "username": "李四", "content": "板凳." },
{ "username": "王五", "content": "地板." }
]
header('Content-Type: application/json; charset=utf-8');json_encode() 將資料編碼為 JSON 字串並輸出<?php
header('Content-Type: application/json; charset=utf-8');
$fruits = [
"fruits" => ["a" => "orange", "b" => "banana", "c" => "apple"],
"numbers" => [1, 2, 3, 4, 5, 6],
"holes" => ["first", 5 => "second", "third"]
];
echo json_encode($fruits, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
?>
輸出結果:
{
"fruits": { "a": "orange", "b": "banana", "c": "apple" },
"numbers": [1, 2, 3, 4, 5, 6],
"holes": { "0": "first", "5": "second", "1": "third" }
}
<?php
header('Content-Type: application/json; charset=utf-8');
// 模擬資料庫查詢結果
$rows = [
['code' => '001', 'name' => '中國', 'addr' => 'Address 11', 'col4' => 'col4 data'],
['code' => '002', 'name' => 'Name 2', 'addr' => 'Address 12', 'col4' => 'col4 data']
];
// 方法一:建構 stdClass 物件(對應 JSON 物件結構)
$obj = new stdClass();
$obj->total = count($rows);
$obj->rows = $rows;
echo json_encode($obj, JSON_UNESCAPED_UNICODE);
// 方法二:直接編碼關聯陣列(輸出為 JSON 物件)
$arr = ['total' => count($rows), 'rows' => $rows];
echo json_encode($arr, JSON_UNESCAPED_UNICODE);
?>
| 常數 | 說明 |
|---|---|
JSON_UNESCAPED_UNICODE | 不將 Unicode 字元轉義為 \uXXXX,直接輸出中文,減少傳輸體積且易讀 |
JSON_UNESCAPED_SLASHES | 不轉義正斜線 / |
JSON_PRETTY_PRINT | 格式化輸出(縮排、換行),除錯時好用,正式環境建議關閉以節省頻寬 |
JSON_NUMERIC_CHECK | 將數字字串轉為數值型態(謹慎使用,可能導致精度問題) |
header() 之前無任何輸出(含 BOM、空白行)JSON_UNESCAPED_UNICODE[];關聯陣列或非連續鍵編碼為 JSON 物件 {}。前端接收時需注意結構差異<?php
header('Content-Type: application/json; charset=utf-8');
// 模擬資料庫查詢
$comments = [
['id' => 1, 'username' => 'Alice', 'content' => 'Great article!', 'time' => '2024-01-15 10:30'],
['id' => 2, 'username' => 'Bob', 'content' => 'Thanks for sharing.', 'time' => '2024-01-15 11:00']
];
echo json_encode([
'status' => 'success',
'data' => $comments,
'total' => count($comments)
], JSON_UNESCAPED_UNICODE);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery + PHP JSON Demo</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="loadBtn">載入留言</button>
<div id="comments"></div>
<script>
$('#loadBtn').click(function() {
$.getJSON('api.php', function(res) {
if (res.status === 'success') {
var html = '';
$.each(res.data, function(i, item) {
html += '<div class="comment">';
html += '<strong>' + item.username + '</strong> ';
html += '<span class="time">' + item.time + '</span><br>';
html += '<p>' + item.content + '</p>';
html += '</div>';
});
$('#comments').html(html);
} else {
alert('載入失敗:' + res.message);
}
}).fail(function() {
alert('請求失敗,請檢查網路或後端服務');
});
});
</script>
</body>
</html>
PHP 輸出 JSON 給 jQuery 的核心在於:設定正確 Header + json_encode() + JSON_UNESCAPED_UNICODE。前端使用 $.getJSON() 或 $.ajax({dataType: 'json'}) 即可自動解析。掌握這套流程,前後端分離開發將更加順暢。