$.post('/api/data', {}, function(data) {
console.log(data.foo); // undefined ❌
console.log(data); // 印出 JSON 字串,非物件
});
原因:未指定 dataType,jQuery 預設智能猜測,低版本可能不自動解析 JSON。
| dataType | 行為 | 回傳 data 型別 |
|---|---|---|
'json' | 強制以 JSON 解析 | Object / Array |
'xml' | 解析為 XML Document | XMLDocument |
'html' | 純文字,執行腳本 | String |
'script' | 載入並執行 JS | String |
'text' | 純文字不處理 | String |
'jsonp' | JSONP 跨域 | Object |
| 未指定 | 根據 Content-Type 智能猜測 | 不確定 |
$.post('/admin/UserBookView.do', {}, function(data) {
console.log(data.result.resultList[0].PRICE); // 3 ✅
}, 'json'); // 第 4 參數指定 dataType
$.post('/admin/UserBookView.do', {}, function(data) {
var datas = eval('(' + data + ')'); // ⚠️ 僅信任來源時使用
console.log(datas.result.resultList[0].PRICE);
});
| 版本 | 預設行為 | 建議做法 |
|---|---|---|
| 1.4 之前 | 不自動解析 JSON | 必須指定 'json' 或手動 parseJSON |
| 1.4 - 1.7 | 依賴 Content-Type header | 建議明確指定 'json' |
| 1.8+ | 嚴格檢查 Content-Type: application/json | 指定 'json' 更保險 |
| 3.0+ | 同上,錯誤處理更完善 | 同左 |
// Java Spring
response.setContentType("application/json;charset=UTF-8");
// PHP
header('Content-Type: application/json; charset=utf-8');
// C# ASP.NET
Response.ContentType = "application/json; charset=utf-8";
// Node.js Express
res.json(data); // 自動設定 header
若後端未設定正確 Content-Type,即使指定 dataType:'json' 也可能解析失敗。
$.ajax({
url: '/api/data',
type: 'POST',
dataType: 'json', // 關鍵
data: { param: 'value' },
success: function(data, textStatus, jqXHR) {
// data 已是解析後的物件
if (data.success) {
renderData(data.result);
} else {
showError(data.message);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// jqXHR.responseText 可能包含錯誤詳情
var msg = '請求失敗: ' + textStatus;
if (jqXHR.responseText) {
try {
var err = $.parseJSON(jqXHR.responseText);
msg += ' - ' + err.message;
} catch (e) {}
}
showError(msg);
}
});
fetch('/api/data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ param: 'value' })
})
.then(res => {
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.json(); // 內建解析
})
.then(data => {
console.log(data.resultList[0].PRICE);
})
.catch(err => console.error(err));
eval(),安全風險極高fetch 或 axios