IndexedDB是一种在客户端(前端)存储数据的数据库API。它允许存储和检索大量结构化数据,可用于创建类似搜索引擎这样的应用程序。下面是一个使用IndexedDB的简单示例,展示了如何创建一个存储并检索数据的网页应用:
- 创建数据库和存储对象:
let databaseName = "myDatabase";
let objectStoreName = "myObjectStore";
let request = indexedDB.open(databaseName, 1);
request.onupgradeneeded = function(event) {
let db = event.target.result;
// 创建一个存储对象,指定唯一的键路径
let objectStore = db.createObjectStore(objectStoreName, { keyPath: "id" });
// 创建索引,以便可以按特定字段进行检索
objectStore.createIndex("name", "name", { unique: false });
};
request.onsuccess = function(event) {
// 数据库打开成功后,可以执行后续操作
let db = event.target.result;
// ...执行其他操作,如添加、更新或删除数据
};
request.onerror = function(event) {
// 数据库打开发生错误时的处理
console.error("Database error: " + event.target.errorCode);
};
- 添加数据到对象存储:
let transaction = db.transaction([objectStoreName], "readwrite");
let objectStore = transaction.objectStore(objectStoreName);
let data = { id: 1, name: "John Doe", age: 30 };
let addRequest = objectStore.add(data);
addRequest.onsuccess = function(event) {
console.log("Data added successfully");
};
addRequest.onerror = function(event) {
console.error("Error adding data: " + event.target.error);
};
- 检索数据:
let transaction = db.transaction([objectStoreName], "readonly");
let objectStore = transaction.objectStore(objectStoreName);
let getRequest = objectStore.get(1);
getRequest.onsuccess = function(event) {
let result = event.target.result;
console.log("Retrieved data:", result);
};
getRequest.onerror = function(event) {
console.error("Error retrieving data: " + event.target.error);
};
这只是一个简单的示例,演示了如何使用IndexedDB在前端进行数据存储和检索。您可以根据自己的需求进行扩展和修改。