上一篇
html5读取数据
- 行业动态
- 2025-05-13
- 5
HTML5支持通过File API读取本地文件,利用LocalStorage实现持久化存储,并可借助Fetch
HTML5读取数据详解
本地存储(LocalStorage & SessionStorage)
- 适用场景:存储简单的键值对数据,如用户偏好设置、临时状态等。
- API方法:
localStorage.getItem(key)
:读取持久化数据。sessionStorage.getItem(key)
:读取会话级数据。
- 示例:
// 写入数据 localStorage.setItem('username', 'John'); // 读取数据 const username = localStorage.getItem('username'); // "John"
- 特点:
- 仅支持字符串类型,需手动序列化/反序列化JSON。
localStorage
数据持久化,sessionStorage
在页面关闭后清除。
IndexedDB
- 适用场景:存储结构化数据(如数据库),支持复杂查询和大量数据。
- 操作步骤:
- 打开数据库:
indexedDB.open(dbName)
。 - 创建对象仓库(Object Store)。
- 使用事务读写数据。
- 打开数据库:
- 示例:
const dbRequest = indexedDB.open('myDB'); dbRequest.onsuccess = (event) => { const db = event.target.result; const transaction = db.transaction(['users'], 'readonly'); const store = transaction.objectStore('users'); const request = store.get('user1'); request.onsuccess = (e) => console.log(e.target.result); };
- 特点:
- 异步操作,需通过事件处理结果。
- 支持索引、键范围查询等高级功能。
File API(读取本地文件)
- 适用场景:用户通过
<input type="file">
选择本地文件后读取内容。 - 核心对象:
FileReader
。 - 示例:
<input type="file" id="fileInput" /> <script> const fileInput = document.getElementById('fileInput'); fileInput.addEventListener('change', (e) => { const file = e.target.files[0]; const reader = new FileReader(); reader.readAsText(file); reader.onload = () => console.log(reader.result); // 文件内容 }); </script>
- 支持格式:
readAsDataURL
:读取为Base64数据。readAsArrayBuffer
:读取为二进制数组。
Fetch API(获取网络数据)
- 适用场景:发起HTTP请求,获取远程资源(如JSON、文本、二进制数据)。
- 基础用法:
fetch('https://api.example.com/data') .then(response => response.json()) // 解析为JSON .then(data => console.log(data));
- POST请求示例:
fetch('https://api.example.com/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) }).then(response => response.json()).then(data => console.log(data));
- 特点:
- 返回Promise,支持
.then()
和async/await
。 - 需处理CORS(跨域资源共享)问题。
- 返回Promise,支持
方法对比表
方法 | 数据类型 | 持久化 | 复杂度 | 适用场景 |
---|---|---|---|---|
LocalStorage | 字符串(JSON) | 是 | 低 | 简单键值对存储 |
IndexedDB | 结构化数据 | 是 | 高 | 复杂数据、大量数据 |
File API | 文件(文本/二进制) | 否 | 中 | 读取本地文件 |
Fetch API | 远程资源(JSON等) | 否 | 中 | 网络请求 |
相关问题与解答
问题1:如何选择LocalStorage、SessionStorage和IndexedDB?
- 解答:
- 若数据是临时会话级(如表单状态),用
SessionStorage
。 - 若数据需长期保存且结构简单(如用户设置),用
LocalStorage
。 - 若数据结构化或需复杂操作(如查询、索引),用
IndexedDB
。
- 若数据是临时会话级(如表单状态),用
问题2:Fetch API如何处理跨域请求?
- 解答:
- 需服务器端设置
Access-Control-Allow-Origin
响应头。 - 客户端可配置
mode: 'cors'
(默认即CORS模式)。 - 示例:
fetch('https://api.example.com/data', { mode: 'cors' }) .then(response => response.json());
- 需服务器端设置