使用 `$.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) { /* ... */ }
});
data: {
data: typename ?? '', // ES2020 Nullish coalescing
// 或
data: (typename !== null && typename !== undefined) ? typename : '',
operationType: '2',
nowheight: nowheight,
nowarea: nowarea
}
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 ?? '';
| 輸入值 | $.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[]` 接收) |
// 表單編碼 (預設)
$.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`)。