如何从索引数据库获取所有值
How to get all values from 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次。我不确定为什么 cursor.continue() 在第 49 次尝试后没有返回 null。任何帮助都非常感谢。
我很肯定这种方法不会多次调用。"数据库已打开"仅记录一个。
只需使用 getAll 函数:
var allRecords = store.getAll();
allRecords.onsuccess = function() {
console.log(allRecords.result);
};
在文档中阅读更多内容:使用 IndexedDB
无需检查 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变量
- 从MySQL数据库中获取输入数据需要两次页面刷新
- 正在从ruby应用程序中的数据库中获取数据
- 在数据库中循环值时,为输入框获取唯一值
- 获取用户位置并将坐标保存在数据库中
- 如何在javascript谷歌地图中获取数据库值
- PHP:获取数据库中多行的变量
- 在流星中获取数据库版本
- 如何获取数据库值并存储在javascript变量中
- 从生成的 PHP-HTML 表中获取数据库值
- 在使用 AJAX 时获取数据库的空值
- 如果我使用Javascript和CSS动态获取数据库的文本,如何将文本划分为列
- 如何使用ajax获取数据库值
- 使用Breeze获取数据库中“忽略”的数据
- 如何在MongoDB中使用NodeJs获取数据库列表
- 使用javascript获取数据库字段值
- 在rails中基于用户选择获取数据库记录
- 如何在grails中从JSON对象中获取数据库变量
- 获取数据库图标图像而不是文本名称
- 如果在数据表中选择了组合框,则获取数据库