我正在将一些数据存储在indexedDb中。
我创建了一种将数据保存到indexedDb中的方法。我已经存储了49条记录。我正在尝试检索所有这些。我写了下面的代码来获取值。我的js文件中除了此行外没有其他代码。
function crap() {
var indexedDb = window.indexedDB || window.webkitIndexedDB || window.msIndexedDB;
var IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange;
var openedDb = indexedDb && indexedDb.open;
var isIndexDbTransactionPossible = window.IDBTransaction || window.webkitIDBTransaction;
if (isIndexDbTransactionPossible) {
isIndexDbTransactionPossible.READ_WRITE = isIndexDbTransactionPossible.READ_WRITE || 'readwrite';
isIndexDbTransactionPossible.READ_ONLY = isIndexDbTransactionPossible.READ_ONLY || 'readonly';
}
var request = indexedDb.open('Offline', DB_VERSION);
request.onupgradeneeded = function(e) {
var db = e.target.result;
if (db.objectStoreNames.contains('tab')) {
db.deleteObjectStore('tab');
}
var store = db.createObjectStore('tab', {keyPath: 'id', autoIncrement: true});
};
request.onsuccess = function(e) {
console.log("DB opened");
var db = e.target.result;
var store= db.transaction('tab', IDBTransaction.READ_ONLY).objectStore('tab');
var cursor = store.openCursor();
cursor.onsuccess = function(event) {
var c = event.target.result;
if (c) {
console.log("New value")
c.continue();
}
};
};
}
我看到“新价值”印刷了124次。我不确定为什么第49次尝试后cursor.continue()不返回null。任何帮助深表感谢。
我很肯定这种方法不会被调用多次。 “ DB打开”仅记录一个。
最佳答案
无需检查readyState,只需检查是否在游标请求回调中定义了游标。这是一个例子。为了清楚起见,我稍微修改了变量的名称。
cursorRequest.onsuccess = function(event) {
var cursor = event.target.result;
if(cursor) {
var value = cursor.value;
console.log('New value:', value);
cursor.continue();
} else {
// Undefined cursor. This means either no objects found,
// or no next object found
// Do not call cursor.continue(); in this else branch because
// there are no more objects over which to iterate.
// Coincidentally, this also means we are done iterating.
console.log('Finished iterating');
}
}
关于javascript - 如何从indexeddb获取所有值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35752789/