萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

jQuery AJAX 傳遞 JSON 到後端常見錯誤與解決方案

現象

使用 `$.ajax` 發送 JSON 物件時,若某屬性值為 `null` 或 `undefined`,該鍵值對**不會被序列化發送**,導致後端接收不到該參數,進而引發「參數缺失」或「空值異常」。

程式碼重現

var typename = null;  // 或 undefined
var nowheight = 100;
var nowarea = 'Taipei';

$.ajax({
  url: '../Services.ashx',
  type: 'POST',
  data: {
    data: typename,           // null/undefined → 不會出現在請求體
    operationType: '2',
    nowheight: nowheight,
    nowarea: nowarea
  },
  success: function(msg) { /* ... */ }
});

瀏覽器開發者工具觀察

  • Network → Payload / Form Data:**缺少 `data` 欄位**
  • 後端 `context.Request.Form["data"]` 回傳 `null` 或拋出例外

解決方案

方案一:前端預設值 (推薦)

data: {
  data: typename ?? '',           // ES2020 Nullish coalescing
  // 或
  data: (typename !== null && typename !== undefined) ? typename : '',
  operationType: '2',
  nowheight: nowheight,
  nowarea: nowarea
}

方案二:強制序列化為 JSON 字串

data: JSON.stringify({
  data: typename,      // 保留 null
  operationType: '2',
  nowheight: nowheight,
  nowarea: nowarea
}),
contentType: 'application/json; charset=utf-8',  // 關鍵:告知伺服器是 JSON
processData: false   // 防止 jQuery 將物件序列化為表單格式

後端需對應讀取 `Request.InputStream` / `php://input` 並 `JSON.parse`。

方案三:後端容錯處理 (防禦性程式設計)

// C# ASP.NET (ASHX/MVC/WebAPI)
string data = context.Request.Form["data"] ?? string.Empty;
// 或
string data = context.Request["data"] ?? string.Empty;  // 同時查 Form/QueryString

// PHP
$data = $_POST['data'] ?? '';  // PHP 7+ null coalescing

// Node.js (Express)
const data = req.body.data ?? '';

深度解析:jQuery 參數序列化規則

輸入值 $.param() 結果 說明
`{a: 'hello'}` `a=hello` 正常
`{a: ''}` `a=` 空字串會發送鍵
`{a: null}` `(空字串)` **鍵被略過**
`{a: undefined}` `(空字串)` **鍵被略過**
`{a: 0}` `a=0` 數值 0 正常發送
`{a: false}` `a=false` 布林值轉字串
`{a: [1,2]}` `a%5B%5D=1&a%5B%5D=2` 陣列展開 (PHP 需 `a[]` 接收)

最佳實務建議

  1. 前端:定義介面介面 (TypeScript interface) 明確標記可選欄位 `data?: string | null`,送前統一 `?? ''` 或 `?? null` (配合 JSON.stringify)。
  2. 傳輸格式統一:全站採用 `contentType: 'application/json'` + `JSON.stringify`,後端統一解析 Raw Body,避免表單編碼歧義。
  3. 後端:建立統一參數綁定/驗證中介軟體,缺失參數回傳 400 錯誤碼並記錄日誌。
  4. API 契約測試:使用 Postman/Newman 或自動化測試驗證「必填欄位缺失」回應符合預期。

相關陷阱:傳統表單 vs JSON

// 表單編碼 (預設)
$.ajax({data: {a:1, b:2}}); 
// → Content-Type: application/x-www-form-urlencoded
// → Body: a=1&b=2

// JSON 編碼
$.ajax({
  data: JSON.stringify({a:1, b:2}),
  contentType: 'application/json',
  processData: false
});
// → Content-Type: application/json
// → Body: {"a":1,"b":2}

**後端接收方式完全不同**:表單用 `Request.Form` / `$_POST`,JSON 用 `Request.InputStream` / `file_get_contents('php://input')` / `req.body` (需 `body-parser`)。

copyright © 萬盛學電腦網 all rights reserved