Fetch API 通过 fetch() 发起请求并处理 Promise,需手动检查 response.ok、设置 headers 和 body(如 POST 时用 JSON.stringify),注意 cookies 需 credentials: 'include',且受 CORS 限制。

使用 Fetch API 获取数据很简单,核心是调用 fetch() 函数并处理返回的 Promise。
大多数场景下,你只需要发起一个 GET 请求并解析 JSON 响应:
fetch() 接收一个 URL 字符串,返回一个 Promise.json()(或其他方法如 .text()、.blob())才能读取内容try/catch 或 .catch() 处理网络错误和解析失败示例:
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
if (!response.ok) throw new Error(`HTTP error: ${response.status}`);
return response.json();
})
.then(data => console.log(data.title))
.catch(err => console.error('加载失败:', err));
配合 async 函数,代码可读性更高,错误处理也更直观:
立即学习“Java免费学习笔记(深入)”;
本地宝团购导航网站v1.2是由本地宝提供API接口调取团购数据,使用本程不用管理接口、数据采集,只需将程序放在网站某文件夹或域名下。程序是经过SEO优化,对提升网站流量有很大帮助,如果你的网站支持rewrite伪静态的话,你可以开启伪静态功能。 后台使用 后台地址:http://域名/admin 帐号密码:jiahai jiahai
0
async function fetchPost() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
console.log(data.title);
} catch (err) {
console.error('请求出错:', err.message);
}
}
fetchPost();
需要设置 method、headers 和 body 选项:
Content-Type 通常设为 'application/json'
body 必须是字符串,所以要用 JSON.stringify()
response.ok 并解析响应体
const postData = { title: 'Hello', body: 'World' };
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(postData)
})
.then(res => res.json())
.then(data => console.log(data.id));
Fetch 不会自动拒绝 HTTP 错误状态(如 404、500),需手动判断 response.ok;它也不会携带 cookies,如需发送 cookie,得加 credentials: 'include';跨域请求受 CORS 限制,服务端必须允许才能成功。
基本上就这些。不复杂但容易忽略细节。
以上就是如何使用JavaScript的Fetch API获取数据?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号