上一篇
html怎么调用api
- 行业动态
- 2025-05-08
- 2553
HTML通过JavaScript调用API,常用
fetch
或 axios
, fetch('API_URL')
获取数据, fetch('API_URL', {method: 'POST', body: data})
发送请求,需处理Promise或使用`async/await
HTML调用API的方法
使用JavaScript的fetch
方法
fetch
是现代浏览器提供的API,用于发起HTTP请求并处理响应。
基本语法:
fetch(url, options) .then(response => response.json()) // 解析为JSON .then(data => { // 处理数据 console.log(data); }) .catch(error => { // 处理错误 console.error('Error:', error); });
示例:调用GET请求的API
<!DOCTYPE html> <html> <head>Fetch API 示例</title> </head> <body> <script> const url = 'https://jsonplaceholder.typicode.com/posts/1'; fetch(url) .then(response => response.json()) .then(data => { document.body.innerHTML = `<h1>${data.title}</h1>`; }) .catch(error => console.error('Error:', error)); </script> </body> </html>
示例:调用POST请求的API
fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ 'foo', body: 'bar', userId: 1 }) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
使用XMLHttpRequest
(传统方法)
XMLHttpRequest
是旧版API,但兼容性更好。
基本步骤:
- 创建
XMLHttpRequest
对象。 - 配置请求(
open
方法)。 - 发送请求(
send
方法)。 - 监听状态变化(
onreadystatechange
)。
示例:
const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1'); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { const data = JSON.parse(xhr.responseText); document.body.innerHTML = `<h1>${data.title}</h1>`; } }; xhr.send();
处理跨域问题(CORS)
如果API服务器未允许跨域请求,浏览器会阻止请求,解决方法:
- 服务器端:设置
Access-Control-Allow-Origin
响应头。 - 客户端:使用代理服务器(如Nginx)或本地开发服务器(如
http-proxy-middleware
)。
常见API调用场景与代码对比
场景 | fetch | XMLHttpRequest |
---|---|---|
GET请求 | 简洁链式调用,支持Promise | 需手动处理状态码和回调 |
POST请求 | 通过body 传递数据,需设置Content-Type | 需手动设置请求头和send 方法 |
错误处理 | .catch 捕获错误 | 需检查xhr.status 和onerror |
兼容性 | 现代浏览器支持,IE需polyfill | 所有浏览器支持 |
相关问题与解答
问题1:如何处理API返回的JSON数据?
解答:
使用response.json()
方法将响应体解析为JSON对象。
fetch('https://api.example.com/data') .then(response => response.json()) // 解析JSON .then(data => console.log(data));
问题2:如何调用需要认证的API?
解答:
在fetch
的headers
中添加认证信息(如Bearer Token):
fetch('https://api.example.com/protected', { headers: { 'Authorization': 'Bearer YOUR_TOKEN_HERE' } }) .then(response => response.json()) .then(data => console.log(data));