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 - 參考示例:待辦事項通知(檢視即時示例)。