如何向浏览器indexDb中存储数据 并如何获取
时间: 2024-01-28 13:04:22 浏览: 23
要向浏览器的 IndexedDB 存储数据,可以使用以下步骤:
1. 打开 IndexedDB 数据库:使用 `window.indexedDB.open()` 方法打开一个数据库,如果数据库不存在,则会创建一个新的数据库。例如:
```javascript
let request = window.indexedDB.open('myDatabase', 1);
```
2. 创建对象存储空间:使用 `IDBDatabase.createObjectStore()` 方法创建一个对象存储空间,可以在其中存储数据。例如:
```javascript
request.onupgradeneeded = function(event) {
let db = event.target.result;
let objectStore = db.createObjectStore('myObjectStore', { keyPath: 'id' });
objectStore.createIndex('name', 'name', { unique: false });
};
```
3. 存储数据:使用 `IDBObjectStore.put()` 方法向对象存储空间中存储数据。例如:
```javascript
let transaction = db.transaction(['myObjectStore'], 'readwrite');
let objectStore = transaction.objectStore('myObjectStore');
let data = { id: 1, name: 'John Doe', age: 30 };
let request = objectStore.put(data);
```
要从 IndexedDB 中获取数据,可以使用以下步骤:
1. 打开 IndexedDB 数据库:同样使用 `window.indexedDB.open()` 方法打开数据库。例如:
```javascript
let request = window.indexedDB.open('myDatabase', 1);
```
2. 获取对象存储空间:使用 `IDBTransaction.objectStore()` 方法获取对象存储空间。例如:
```javascript
let transaction = db.transaction(['myObjectStore'], 'readonly');
let objectStore = transaction.objectStore('myObjectStore');
```
3. 获取数据:使用 `IDBObjectStore.get()` 方法从对象存储空间中获取数据。例如:
```javascript
let request = objectStore.get(1);
request.onsuccess = function(event) {
let data = event.target.result;
console.log(data);
};
```
以上就是向 IndexedDB 存储数据和获取数据的基本步骤。需要注意的是,IndexedDB 是异步的,需要使用回调函数来处理操作结果。