Fetch API
下面是使用 Fetch API 实现 AJAX 请求 JSON 数据的示例。这是现代浏览器中推荐的方式,语法更简洁,基于 Promise。
✅ 示例:使用 Fetch API 获取 JSON 数据
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Fetch API JSON 示例</title>
</head>
<body>
<h2>用户信息:</h2>
<div id="user"></div>
<script>
fetch("user.json")
.then(response => {
if (!response.ok) {
throw new Error("网络响应错误:" + response.status);
}
return response.json(); // 将响应解析为 JSON
})
.then(data => {
document.getElementById("user").innerHTML =
"姓名:" + data.name + "<br>年龄:" + data.age;
})
.catch(error => {
console.error("请求失败:", error);
});
</script>
</body>
</html>
示例 JSON 文件(user.json)
{
"name": "李四",
"age": 35
}
✅ 使用 Fetch API 发送 POST 请求(附带 JSON 数据)
fetch("https://example.com/api/user", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "王五",
age: 22
})
})
.then(response => response.json())
.then(result => {
console.log("服务器返回结果:", result);
})
.catch(error => {
console.error("提交失败:", error);
});
📝 提示:
fetch()
默认是 GET 请求。- 要处理非 200 状态码,需要手动判断
response.ok
。 fetch()
不会像 jQuery 那样自动 reject 非 2xx 状态,需要自己写错误判断。
如果你想结合后端接口使用、处理跨域、或异步/await 写法的例子,我也可以继续扩展。需要的话请说一声。