本文介绍了如何从IndexedDB中的objectstore.put()返回自动增量ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用objectstore.put()将记录插入IndexedDB后,如何返回自动递增的ID?
How do I return the auto incremented ID after inserting a record into an IndexedDB using objectstore.put()?
下面是我的代码:
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);
};
};
推荐答案
使用 e.target.result
.由于API是异步的,因此必须使用callback来获取返回值,如下所示:
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);
};
};
这篇关于如何从IndexedDB中的objectstore.put()返回自动增量ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!