怎样在HTML中获取数据?
酷盾叔
•
•
前端开发 •
阅读 0
在HTML中获取数据主要通过JavaScript实现,常见方法包括使用fetch API或XMLHttpRequest发起HTTP请求,以及通过DOM操作获取表单输入值或元素内容,也可结合WebSocket实时接收数据。
在网页开发中,HTML本身是静态标记语言,但通过与JavaScript、表单和现代API配合,可以实现多种数据获取方案,以下是五种主流方法,覆盖从基础到高级场景:

<section>
<h2>一、表单提交:传统页面级数据交互</h2>
<div class="code-block">
<pre><code><form action="/submit" method="POST">
<input type=”text” name=”username” required>
<input type=”email” name=”email”>
<button type=”submit”>提交</button>
</form>
- GET方法:数据通过URL参数传递(适合搜索场景)
- POST方法:数据在HTTP body中传输(适合敏感数据)
- 局限:会触发页面刷新,体验较差
<section>
<h2>二、AJAX技术:无刷新数据获取</h2>
<h3>1. 经典XMLHttpRequest</h3>
<div class="code-block">
<pre><code>const xhr = new XMLHttpRequest();
xhr.open(‘GET’, ‘/api/data’);
xhr.onload = () => {
if (xhr.status === 200) {
console.log(JSON.parse(xhr.response));
}
};
xhr.send();
<h3>2. 现代Fetch API(推荐)</h3>
<div class="code-block">
<pre><code>fetch('/api/products')
.then(response => response.json())
.then(data => renderProducts(data))
.catch(error => console.error(‘请求失败:’, error));