IDBTransaction: commit() 方法
注意:此功能在 Web Workers 中可用。
commit() 方法是 IDBTransaction 介面的一個方法,如果在一個活躍的事務上呼叫,則會提交該事務。
請注意,通常不必顯式呼叫 commit() —— 當所有掛起的請求都已滿足且沒有新的請求被髮出時,事務將自動提交。commit() 可用於啟動提交過程,而無需等待掛起請求的事件被分派。
如果在非活躍事務上呼叫該方法,則會丟擲一個 InvalidStateError DOMException。
語法
js
commit()
引數
無。
返回值
無(undefined)。
異常
InvalidStateErrorDOMException-
如果事務狀態不是活躍狀態,則丟擲此異常。
示例
js
const note = document.getElementById("notifications");
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["myDB"], "readwrite");
// report on the success of opening the transaction
transaction.oncomplete = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Transaction completed: database modification finished.";
};
transaction.onerror = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Transaction not opened due to error. Duplicate items not allowed.";
};
// create an object store on the transaction
const objectStore = transaction.objectStore("myObjStore");
// add our newItem object to the object store
const objectStoreRequest = objectStore.add(newItem[0]);
objectStoreRequest.onsuccess = (event) => {
// report the success of the request (this does not mean the item
// has been stored successfully in the DB - for that you need transaction.onsuccess)
note.appendChild(document.createElement("li")).textContent =
"Request successful.";
};
// Force the changes to be committed to the database asap
transaction.commit();
規範
| 規範 |
|---|
| Indexed Database API 3.0 # ref-for-dom-idbtransaction-commit② |
瀏覽器相容性
載入中…
另見
- 使用 IndexedDB
- 開始事務:
IDBDatabase - 使用事務:
IDBTransaction - 設定鍵的範圍:
IDBKeyRange - 檢索和修改資料:
IDBObjectStore - 使用遊標:
IDBCursor - 參考示例:待辦事項通知(檢視即時示例)。