首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 回傳 JSON 給 jQuery 完整實作:資料庫編碼、解碼與前後端串接

     編輯:PHP 相關知識

JSON 格式基礎

JSON (JavaScript Object Notation) 是輕量級資料交換格式,PHP 5.2+ 內建 json_encode() / json_decode()。

PHP 輸出 JSON 給前端

必要標頭設定

<?php
header('Content-Type: application/json; charset=utf-8'); // 標準 MIME
// 或舊版相容
header('Content-Type: text/json; charset=utf-8');

陣列/物件編碼輸出

<?php
$data = [
    'status' => 'success',
    'users' => [
        ['id' => 1, 'name' => '張三', 'email' => 'zhang@example.com'],
        ['id' => 2, 'name' => '李四', 'email' => 'li@example.com']
    ],
    'meta' => ['total' => 2, 'page' => 1]
];
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

常用選項:

  • JSON_UNESCAPED_UNICODE:中文不轉 \uXXXX,可讀性佳
  • JSON_PRETTY_PRINT:縮排格式化(開發除錯用)
  • JSON_UNESCAPED_SLASHES:不轉義 /
  • JSON_NUMERIC_CHECK:數值字串轉數字(謹慎使用)

資料庫資料轉 JSON 兩種架構

方式一:物件導向(stdClass)

<?php
// 假設從資料庫查詢得到
$rows = [
    ['code' => '001', 'name' => '台灣', 'population' => 23000000],
    ['code' => '002', 'name' => '日本', 'population' => 125000000]
];

$obj = new stdClass();
$obj->total = count($rows);
$obj->rows = $rows;

echo json_encode($obj, JSON_UNESCAPED_UNICODE);
// {"total":2,"rows":[{"code":"001","name":"台灣",...},...]}

// 前端存取:data.rows[0].name

方式二:純陣列結構

<?php
$arr = [
    'total' => count($rows),
    'rows' => $rows
];
echo json_encode($arr, JSON_UNESCAPED_UNICODE);
// 前端存取:data.rows[0].name (同樣運作)

現代 API 慣用純陣列結構,序列化/反序列化更直觀。

完整範例:資料庫查詢 + JSON API

<?php
// api/users.php
header('Content-Type: application/json; charset=utf-8');

try {
    $pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'user', 'pass');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $page = max(1, (int)($_GET['page'] ?? 1));
    $limit = 10;
    $offset = ($page - 1) * $limit;

    $stmt = $pdo->prepare('SELECT id, username, email, created_at FROM users LIMIT ? OFFSET ?');
    $stmt->bindValue(1, $limit, PDO::PARAM_INT);
    $stmt->bindValue(2, $offset, PDO::PARAM_INT);
    $stmt->execute();
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $totalStmt = $pdo->query('SELECT COUNT(*) FROM users');
    $total = $totalStmt->fetchColumn();

    echo json_encode([
        'success' => true,
        'data' => $users,
        'pagination' => [
            'page' => $page,
            'limit' => $limit,
            'total' => (int)$total,
            'pages' => (int)ceil($total / $limit)
        ]
    ], JSON_UNESCAPED_UNICODE);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Database error',
        'message' => $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}

jQuery 前端串接

$.getJSON 簡易版

<script>
$.getJSON('api/users.php', {page: 1}, function(response) {
    if (response.success) {
        let html = '';
        $.each(response.data, function(i, user) {
            html += `<div class="user"><h4>${user.username}</h4><p>${user.email}</p></div>`;
        });
        $('#user-list').html(html);
        // 處理分頁...
    } else {
        alert('錯誤:' + response.error);
    }
}).fail(function() {
    alert('網路請求失敗');
});
</script>

$.ajax 完整控制版

<script>
$.ajax({
    url: 'api/users.php',
    method: 'GET',
    dataType: 'json',
    data: {page: 1},
    beforeSend: function() { $('#loading').show(); },
    success: function(response) { /* ... */ },
    error: function(xhr, status, error) {
        console.error('AJAX Error:', status, error);
    },
    complete: function() { $('#loading').hide(); }
});
</script>

JSON 解碼回 PHP

<?php
$json = '{"name":"張三","age":25,"skills":["PHP","JS","MySQL"]}';

// 解碼為關聯陣列(推薦,true 參數)
$arr = json_decode($json, true);
// ['name' => '張三', 'age' => 25, 'skills' => ['PHP','JS','MySQL']]

// 解碼為物件(預設)
$obj = json_decode($json);
// $obj->name, $obj->skills[0]

// 錯誤處理
$data = json_decode($input, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    throw new Exception('JSON 解析失敗:' . json_last_error_msg());
}

常見問題與解決

問題原因解決
中文變 \uXXXX預設編碼行為加 JSON_UNESCAPED_UNICODE
數字變字串資料庫驅動回傳字串JSON_NUMERIC_CHECK 或 PDO ATTR_STRINGIFY_FETCHES => false
前端收到亂碼編碼不一致確認 PHP 檔案 UTF-8、資料庫 utf8mb4、header charset=utf-8
大數值精度遺失JS Number 限制ID 等大數值以字串輸出
json_decode 回傳 nullJSON 格式錯誤/深度超限檢查 json_last_error()、調整 json_decode($json, true, 512) 深度

最佳實踐總結

  1. 統一使用 application/json + charset=utf-8
  2. 永遠加 JSON_UNESCAPED_UNICODE
  3. API 回應固定結構:{success, data, error, pagination}
  4. 錯誤時回傳適當 HTTP 狀態碼(4xx, 5xx)
  5. 前端統一錯誤處理攔截器
  6. 敏感資料(密碼、Token)勿輸出至 JSON

掌握 JSON 編解碼與前後端串接,是現代 PHP 開發核心技能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved