IDBObjectStore: get() 方法
注意:此功能在 Web Workers 中可用。
get() 方法是 IDBObjectStore 接口的一部分,它返回一个 IDBRequest 对象,并在单独的线程中返回由指定键选择的对象。该方法用于从对象存储中检索特定记录。
如果成功找到值,则会创建一个该值的结构化克隆,并将其设置为请求对象的 result 属性。
注意:此方法对于以下两种情况会产生相同的结果:a) 数据库中不存在的记录,b) 值为 undefined 的记录。要区分这两种情况,请使用相同的键调用 openCursor() 方法。如果记录存在,该方法会提供一个游标;如果不存在,则不提供游标。
语法
js
get(key)
参数
key-
用于标识要检索的记录的键或键范围。
返回值
一个 IDBRequest 对象,后续与此操作相关的事件会在此对象上触发。
如果操作成功,请求的 result 属性的值将是与给定键或键范围匹配的第一条记录的值。
异常
此方法可能会抛出以下类型之一的DOMException:
TransactionInactiveErrorDOMException-
如果此
IDBObjectStore的事务不活跃,则会抛出此异常。 DataErrorDOMException-
如果提供的键或键范围包含无效键,则会抛出此异常。
InvalidStateErrorDOMException-
如果
IDBObjectStore已被删除或移除,则会抛出此异常。
示例
在以下代码片段中,我们打开数据库的读/写事务,并使用 get() 方法从对象存储中获取一条特定记录——一个键为 "Walk dog" 的示例记录。检索到此数据对象后,您可以使用常规的 JavaScript 更新它,然后使用 IDBObjectStore.put 操作将其放回数据库。完整的可运行示例,请参见我们的 待办事项通知 应用(在线查看示例)。
js
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.onsuccess = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Database initialized.";
// store the result of opening the database in the db variable.
// This is used a lot below
db = DBOpenRequest.result;
// Run the getData() function to get the data from the database
getData();
};
function getData() {
// open a read/write db transaction, ready for retrieving the data
const transaction = db.transaction(["toDoList"], "readwrite");
// report on the success of the transaction completing, when everything is done
transaction.oncomplete = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Transaction completed.";
};
transaction.onerror = (event) => {
note.appendChild(document.createElement("li")).textContent =
`Transaction not opened due to error: ${transaction.error}`;
};
// create an object store on the transaction
const objectStore = transaction.objectStore("toDoList");
// Make a request to get a record by key from the object store
const objectStoreRequest = objectStore.get("Walk dog");
objectStoreRequest.onsuccess = (event) => {
// report the success of our request
note.appendChild(document.createElement("li")).textContent =
"Request successful.";
const myRecord = objectStoreRequest.result;
};
}
规范
| 规范 |
|---|
| Indexed Database API 3.0 # ref-for-dom-idbobjectstore-get① |
浏览器兼容性
加载中…
另见
- 使用 IndexedDB
- 开始事务:
IDBDatabase - 使用事务:
IDBTransaction - 设置键的范围:
IDBKeyRange - 检索和修改数据:
IDBObjectStore - 使用游标:
IDBCursor - 参考示例:待办事项通知(查看实时示例)。