【发布时间】:2016-03-02 16:23:41
【问题描述】:
我正在将一些数据存储在 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.transaction('tab').objectStore('tab').count().onsuccess = function(e) { console.log(e.target.result); } 节目?
-
(它可能只是调试代码,但是在 onsuccess 处理程序中检查 readyState 是没有意义的。只有当请求的 readyState 为“done”时,才会在请求中触发“success”事件。)跨度>
-
@JoshuaBell:是的。这只是为了调试。它没有给代码增加任何价值。
-
您的代码看起来不错。所以是时候质疑你的假设了。验证存储中的记录数。记录 cursor.key 每次迭代,看看有什么意外记录。
-
另外,请确保您没有其他代码干扰。如果您有稍后的代码 - 未显示 - 覆盖光标,您可能会看到迭代不同商店的结果。
标签: javascript html indexeddb