萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery AJAX 獲取 JSON 數據完整實戰:前後端交互、錯誤處理、最佳實踐

前端頁面結構

<ul id="userList">
  <li><a href="#" data-id="1">張三</a></li>
  <li><a href="#" data-id="2">李四</a></li>
  <li><a href="#" data-id="3">王五</a></li>
</ul>
<div id="userInfo" style="display:none;">
  <p>姓名:<span id="name"></span></p>
  <p>性別:<span id="sex"></span></p>
  <p>電話:<span id="tel"></span></p>
  <p>郵箱:<span id="email"></span></p>
</div>

jQuery AJAX 交互邏輯

$(function() {
  $('#userList a').on('click', function(e) {
    e.preventDefault();
    var userId = $(this).data('id');
    var $info = $('#userInfo').show();

    // 顯示加載狀態
    $info.find('span').text('載入中...');

    $.ajax({
      url: 'server.php',
      type: 'GET',
      data: { action: 'getUser', id: userId },
      dataType: 'json', // 關鍵:自動解析 JSON,回調直接得對象
      cache: false,
      timeout: 5000,
      success: function(user) {
        if (user && user.id) {
          $('#name').text(user.username);
          $('#sex').text(user.sex);
          $('#tel').text(user.tel);
          $('#email').text(user.email);
        } else {
          $info.find('span').text('用戶不存在');
        }
      },
      error: function(xhr, status, error) {
        $info.find('span').text('請求失敗: ' + status);
        console.error('AJAX Error:', status, error, xhr.responseText);
      }
    });
  });
});

後端 PHP (server.php)

<?php
header('Content-Type: application/json; charset=utf-8');
require_once 'db.php'; // PDO 連接

$action = $_GET['action'] ?? '';
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($action === 'getUser' && $id > 0) {
  $stmt = $pdo->prepare('SELECT username, sex, tel, email FROM users WHERE id = ?');
  $stmt->execute([$id]);
  $user = $stmt->fetch(PDO::FETCH_ASSOC);
  echo json_encode($user ?: ['error' => 'Not found']);
  exit;
}
echo json_encode(['error' => 'Invalid request']);

MySQL 表結構

CREATE TABLE `users` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `username` VARCHAR(100) NOT NULL,
  `sex` VARCHAR(10) NOT NULL,
  `tel` VARCHAR(50) NOT NULL,
  `email` VARCHAR(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

$.getJSON 簡寫版

$.getJSON('server.php', { action: 'getUser', id: userId }, function(user) {
  // 成功回調,user 已是對象
}).fail(function(xhr, status, error) {
  // 失敗處理
});

進階:統一錯誤處理與 Loading 管理

// 全局 AJAX 設置
$.ajaxSetup({
  dataType: 'json',
  cache: false,
  beforeSend: function(xhr) {
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    $('#globalLoading').show();
  },
  complete: function() { $('#globalLoading').hide(); },
  error: function(xhr, status, error) {
    var msg = '請求失敗';
    if (xhr.responseJSON && xhr.responseJSON.message) msg = xhr.responseJSON.message;
    else if (status === 'timeout') msg = '請求超時';
    else if (status === 'parsererror') msg = '數據格式錯誤';
    showToast(msg);
  }
});

// 業務代碼極簡
$('#userList a').click(function(e) {
  e.preventDefault();
  $.get('server.php', { action: 'getUser', id: $(this).data('id') })
    .done(function(user) { renderUser(user); });
});

JSONP 跨域方案(舊項目)

// 前端
$.ajax({
  url: 'https://api.other.com/user',
  dataType: 'jsonp', // 自動添加 callback=xxx 參數
  jsonp: 'callback', // 參數名,默認 callback
  success: function(data) { /* ... */ }
});

// 後端 PHP
$callback = $_GET['callback'] ?? 'callback';
$data = ['username' => '張三', 'sex' => '男'];
echo $callback . '(' . json_encode($data) . ')'; // 輸出: callback({"username":"張三","sex":"男"})

現代項目優先用 CORS (Access-Control-Allow-Origin),JSONP 僅支持 GET、有安全風險。

安全建議

  • 後端設置 header('Content-Type: application/json; charset=utf-8') 防止 XSS(瀏覽器不會將 JSON 執行腳本)。
  • 輸出前轉義:json_encode($data, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP)。
  • 敏感操作驗證 CSRF Token。
  • 限制 JSONP 回調函數名格式(僅允許字母數字下劃線)。

總結

jQuery $.ajax(dataType:'json') / $.getJSON 讓前後端 JSON 交互極其簡單。關鍵在於:後端正確設置 Content-Type、錯誤統一格式、前端統一異常處理、安全防護。現代項目建議改用 Fetch API + 統一攔截器,邏輯更清晰、支持流式處理。

copyright © 萬盛學電腦網 all rights reserved