7

使用 objectstore.put() 将记录插入 IndexedDB 后,如何返回自动递增的 ID?

下面是我的代码:

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);
    };
};
4

2 回答 2

10

使用e.target.result. 由于 API 是异步的,因此您必须使用回调来获取返回值,如下所示:

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);
    };
};
于 2012-09-20T05:54:57.927 回答
1

解决了。您可以使用request.result.

于 2012-09-19T21:18:42.000 回答