HTML本身不能直接访问接口,但通过JavaScript的fetch或AJAX方法可实现与后端API交互。fetch基于Promise,语法简洁,适用于现代浏览器;AJAX兼容旧版本浏览器,适合老旧环境。两者均可发送GET、POST请求,获取并动态更新数据。在HTML中通过<script>标签集成JavaScript代码,可监听事件或页面加载时调用API。需注意CORS、错误处理、敏感信息保护及用户体验。推荐新项目使用fetch,旧项目兼容考虑AJAX。核心为HTML提供结构,JavaScript实现通信。

在现代网页开发中,HTML 本身不能直接“访问”接口,但结合 JavaScript 可以轻松实现与后端 API 的数据交互。通过 fetch 或传统的 AJAX(XMLHttpRequest) 方法,前端页面可以发送请求、获取数据并动态更新内容。
fetch 是现代浏览器提供的原生方法,用于发起网络请求,语法简洁,基于 Promise,适合处理异步操作。
基本 GET 请求示例:
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) throw new Error('网络错误');
return response.json();
})
.then(data => {
console.log(data); // 处理返回的数据
document.getElementById('result').innerText = JSON.stringify(data);
})
.catch(err => console.error('请求失败:', err));
POST 请求发送数据:
立即学习“前端免费学习笔记(深入)”;
fetch('https://api.example.com/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: 'user',
password: 'pass'
})
})
.then(res => res.json())
.then(data => console.log(data));
AJAX 是较早的技术,兼容老版本浏览器,适用于不支持 fetch 的环境。
AJAX GET 请求示例:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
document.getElementById('output').innerHTML = data.message;
}
};
xhr.send();
AJAX POST 请求:
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/submit', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 201) {
console.log('提交成功:', xhr.responseText);
}
};
xhr.send(JSON.stringify({ name: '张三', age: 25 }));
将 JavaScript 写在 HTML 文件的 <script> 标签中,监听事件或在页面加载时自动请求数据。
简单 HTML 示例:
<!DOCTYPE html>
<html>
<head><title>API 测试</title></head>
<body>
<button onclick="getData()">获取数据</button>
<div id="result"></div>
<script>
function getData() {
fetch('/api/user')
.then(res => res.json())
.then(data => {
document.getElementById('result').innerText = `姓名:${data.name}`;
});
}
</script>
</body>
</html>
以上就是html如何访问接口_HTML接口(API)调用(fetch/AJAX)与数据交互方法的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号