
本文详解如何在事件处理函数(如按钮点击)中正确调用 fetch 并解析 JSON 响应,重点纠正 res.json 未加括号导致返回函数体而非执行解析的常见错误。
本文详解如何在事件处理函数(如按钮点击)中正确调用 `fetch` 并解析 json 响应,重点纠正 `res.json` 未加括号导致返回函数体而非执行解析的常见错误。
在前端开发中,fetch() 是发起网络请求的标准方式,常用于从本地 JSON 文件或 API 端点获取数据。但初学者常因忽略 .json() 是一个需调用的方法(而非属性),写出 res.json(无括号)——这会导致后续 data 实际为函数定义字符串(如 f json() { [native code] }),而非解析后的对象。
✅ 正确写法:必须调用 .json()
function OnClick() {
fetch('./Data.json')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json(); // ✅ 关键:带括号,执行解析
})
.then(data => {
console.log('成功获取数据:', data);
// 此处可进一步操作 DOM,例如显示数据
})
.catch(error => {
console.error('请求失败:', error);
// 建议向用户提示错误(如显示警告信息)
});
}
⚠️ 注意事项
-
.json()返回 Promise:它本身是异步操作,必须用.then()或await处理其返回值; -
始终检查
response.ok:HTTP 404、500 等错误状态不会自动抛出异常,需手动判断; -
避免
.then(res => res.json):这是最常见错误——仅引用函数而不调用,结果data变成函数对象; -
推荐使用
async/await提升可读性(现代写法):
async function OnClick() {
try {
const response = await fetch('./Data.json');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json(); // ✅ 清晰、顺序明确
console.log(data);
} catch (error) {
console.error('加载数据失败:', error);
}
}
? 小结
fetch 在函数中使用的本质是:链式处理 Promise + 正确调用响应方法。只要牢记 res.json()、res.text()、res.blob() 等均为需执行的方法,且需配合错误处理与状态校验,就能稳定实现点击触发的数据加载功能。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











