javascript - 如何从 indexeddb 中获取所有值

标签 javascript html indexeddb

我正在努力将一些数据存储在 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();
        }
    };
};
}

我看到“New Value”打印了 124 次。我不确定为什么 cursor.continue() 在第 49 次尝试后没有返回 null。非常感谢任何帮助。

我确信此方法不会被调用多次。 “DB opened”只记录一个。

最佳答案

只需使用 getAll 函数:

    var allRecords = store.getAll();
    allRecords.onsuccess = function() {
        console.log(allRecords.result);
    };

阅读文档中的更多信息:Working with IndexedDB

关于javascript - 如何从 indexeddb 中获取所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35752789/

相关文章:

javascript - `Math` 可以按照结构化克隆算法克隆吗?

javascript - 尝试从 jQuery.get() 返回值,总是以未定义结束

javascript - 如何在函数参数上使用模板文字?

javascript - angularjs通过父级的索引获取td

javascript - 如何根据该json数组中的特定属性和angular js中其他下拉列表的ng-model值过滤ng-repeat中的数组

php - 在服务器端保存大量数组的最佳方法

javascript - 有没有使用 Angular.js 和 Indexed DB 的好方法?

javascript - react : onChange callback not firing

javascript - 无法将 JQuery 表单验证与两个按钮 html 表单一起使用

javascript - 插入循环后,indexedDB 阻止了 DOM 异常