问题
How do I return the auto incremented ID after inserting a record into an IndexedDB using objectstore.put()?
Below is my code:
idb.indexedDB.addData = function (objectStore, data) {
var db = idb.indexedDB.db;
var trans = db.transaction([objectStore], READ_WRITE);
var store = trans.objectStore(objectStore);
var request = store.put(data);
request.onsuccess = function (e) {
//Success, how do I get the auto incremented id?
};
request.onerror = function (e) {
console.log("Error Adding: ", e);
};
};
回答1:
Use e.target.result
. Since the API is async, you must use callback to get the return value, as follow:
idb.indexedDB.addData = function (objectStore, data, callback) {
var db = idb.indexedDB.db;
var trans = db.transaction([objectStore], READ_WRITE);
var store = trans.objectStore(objectStore);
var request = store.put(data);
request.onsuccess = function (e) {
callback(e.target.result);
};
request.onerror = function (e) {
console.log("Error Adding: ", e);
callback(undefined);
};
};
回答2:
Solved. You can get the incremented id by using request.result
.
来源:https://stackoverflow.com/questions/12502830/how-to-return-auto-increment-id-from-objectstore-put-in-an-indexeddb