**Ajax 獲取 JSON 字符串後,必須使用 `JSON.parse()` 解析,嚴禁使用 `eval()`。**
const jsonStr = '{"name": "周星馳", "age": 23}';
// ❌ 方法 1:eval() - 危險
const obj1 = eval('(' + jsonStr + ')'); // 需包裹括號
console.log(obj1.name); // "周星馳"
// ✅ 方法 2:JSON.parse() - 標準、安全
const obj2 = JSON.parse(jsonStr);
console.log(obj2.name); // "周星馳"
const malicious = '{"name": "alert(\'XSS\')", "age": 23}';
// eval() 會執行惡意代碼!
try {
eval('(' + malicious + ')'); // 彈窗 "XSS"!代碼被執行了!
} catch(e) {}
// JSON.parse() 僅解析為字符串,不執行
try {
const obj = JSON.parse(malicious);
console.log(obj.name); // "alert('XSS')" - 純文本,安全
} catch(e) {
console.log('解析失敗:', e.message); // 如果 JSON 格式非法會拋錯
}
// 後端返回給前端的必須是「字符串」
// 因為 HTTP 傳輸的是文本,不是 JavaScript 對象
// 後端 (Node.js)
res.json({name: '周星馳'});
// 實際發送: '{"name":"周星馳"}' (字符串)
// 前端接收
fetch('/api').then(r => r.text()).then(str => {
// str 是字符串 '{"name":"周星馳"}'
// 必須 parse 才能變成對象
const obj = JSON.parse(str);
});
// 現代 Fetch API (推薦)
async function fetchJson(url, options = {}) {
try {
const response = await fetch(url, {
headers: {'Accept': 'application/json', ...options.headers},
credentials: 'include', // 攜帶 Cookie
...options
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
// 關鍵:response.json() 內部使用 JSON.parse(),自動處理
const data = await response.json();
return data;
} catch (error) {
// 網絡錯誤、解析錯誤、HTTP 錯誤統一捕獲
console.error('API 請求失敗:', error);
throw error;
}
}
// 使用
fetchJson('/api/user').then(user => console.log(user.name));
$.ajax({
url: '/api/data',
dataType: 'json', // 關鍵:自動調用 JSON.parse()
success: function(data) {
// data 已是對象,直接使用
console.log(data.name);
},
error: function(xhr, status, error) {
if (status === 'parsererror') {
alert('服務端返回非法 JSON');
}
}
});