萬盛學電腦網

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

jQuery 處理 JSON 與 AJAX 返回 JSON 完整實戰指南

JSON 基礎結構速覽

// 物件
{"areaId": "123", "name": "Taipei"}

// 陣列
["apple", "banana", "orange"]

// 物件陣列(最常見 API 回應格式)
[
  {"id": 1, "name": "Item 1"},
  {"id": 2, "name": "Item 2"}
]

// 巢狀物件
{
  "areas": [
    {"id": "123", "name": "North"},
    {"id": "456", "name": "South"}
  ]
}

JavaScript 操作 JSON:字串 vs 物件

JSON 字串 → 物件

// 1. jQuery 解析(內部用 JSON.parse)
var jsonStr = '{"id":1,"name":"Mary"}';
var obj = $.parseJSON(jsonStr);  // 或 JSON.parse(jsonStr)
console.log(obj.name);  // 'Mary'

// 2. $.getJSON 自動解析
$.getJSON('/api/user', function(obj) {
  // obj 已是物件,無需手動解析
  console.log(obj.name);
});

物件 → JSON 字串

var obj = { id: 1, name: 'Mary', tags: ['a', 'b'] };
var jsonStr = JSON.stringify(obj);
// '{"id":1,"name":"Mary","tags":["a","b"]}'

// 發送給後端
$.ajax({
  url: '/api/save',
  type: 'POST',
  contentType: 'application/json',
  data: JSON.stringify(obj),
  success: function(res) { ... }
});

AJAX 返回 JSON 處理模式

模式一:dataType: 'json'(推薦)

$.ajax({
  url: '/api/users',
  type: 'GET',
  dataType: 'json',  // 關鍵:自動 parseJSON
  success: function(data) {
    // data 直接是物件/陣列
    $.each(data, function(i, user) {
      console.log(user.id, user.name);
    });
  },
  error: function(xhr, status, err) {
    console.error('AJAX 失敗:', status, err);
  }
});

模式二:手動解析(舊版 jQuery 或非標準回應)

$.ajax({
  url: '/legacy/api',
  type: 'POST',
  dataType: 'text',  // 不自動解析
  success: function(text) {
    try {
      var data = $.parseJSON(text);  // 或 JSON.parse(text)
      // 處理 data
    } catch (e) {
      console.error('JSON 解析失敗:', text);
    }
  }
});

模式三:$.post / $.get 簡寫

// jQuery 1.4+ 自動偵測 JSON 回應(需正確 Content-Type)
$.post('/api/save', { id: 1, name: 'Test' }, function(data) {
  // 高版本 jQuery:data 已是物件
  // 低版本:data 可能是字串,需 $.parseJSON(data)
  console.log(data.success);
}, 'json');  // 強制指定預期類型

後端輸出 JSON 範例

PHP

<?php
header('Content-Type: application/json; charset=utf-8');
$data = [
  'red' => ['id' => 1, 'name' => 'Mary'],
  'blue' => ['id' => 2, 'name' => '燕子']
];
echo json_encode($data, JSON_UNESCAPED_UNICODE);
// {"red":{"id":1,"name":"Mary"},"blue":{"id":2,"name":"燕子"}}
?>

Java (Spring)

@RestController
public class UserController {
  @GetMapping("/api/user")
  public User getUser() {
    return new User(1, "Mary");  // Jackson 自動序列化為 JSON
  }
}

ASP.NET (C#)

public ActionResult GetUser() {
  var user = new { id = 1, name = "Mary" };
  return Json(user, JsonRequestBehavior.AllowGet);
}

遍歷 JSON 物件/陣列

var data = {
  "red": {"id": 1, "name": "Mary"},
  "blue": {"id": 2, "name": "燕子"}
};

// 方法一:$.each(推薦,支援物件與陣列)
$.each(data, function(key, item) {
  console.log(key, item.id, item.name);
});

// 方法二:for...in(僅物件)
for (var key in data) {
  if (data.hasOwnProperty(key)) {
    console.log(key, data[key].id);
  }
}

// 方法三:Object.keys + forEach(ES5+)
Object.keys(data).forEach(function(key) {
  console.log(key, data[key].name);
});

常見坑點與避雷

  • Content-Type 必須正確:application/json; charset=utf-8,否則 jQuery 可能不自動解析
  • 雙重解析錯誤:已是物件又呼叫 $.parseJSON() → 拋錯
  • 單引號非標準 JSON:{'a':1} ❌,必須雙引號 {"a":1}
  • 後端輸出多餘內容:如警告訊息、HTML、BOM → 導致解析失敗
  • 大數字精度:JS Number 精度 53 位,長整數 (id > 2^53) 需以字串傳輸

現代最佳實踐:Fetch + JSON

async function fetchUsers() {
  try {
    const response = await fetch('/api/users');
    if (!response.ok) throw new Error('HTTP ' + response.status);
    const data = await response.json();  // 內建解析
    return data;
  } catch (err) {
    console.error('Fetch 失敗:', err);
  }
}

// 使用
fetchUsers().then(users => {
  users.forEach(u => console.log(u.name));
});

總結

  • 前端:dataType: 'json' 讓 jQuery 自動處理,或用 fetch().json()
  • 後端:設定正確 Content-Type,輸出標準 JSON(雙引號、無 BOM、無多餘輸出)
  • 除錯:Network 面板檢查 Raw Response,確認是純 JSON
  • 大數字:ID 用字串傳輸,避免精度丟失
copyright © 萬盛學電腦網 all rights reserved