我正在使用 IndexedDB
,我有一个包含大约 4000 条记录的数据库。我试图一次加载一小块记录。类似于您在推特上看到的无限滚动。我尝试用谷歌搜索这个并没有找到代码示例,但遇到了高级方法。我尝试使用它,但仍然没有成功。浏览器一次加载所有记录。如何才能一次只加载少量记录?
var openRequest = indexedDB.open("USA", 1);
openRequest.onsuccess = function (e) {
var db = e.target.result;
var transaction = db.transaction(["Male"], "readonly");
var objectStore = transaction.objectStore("Male");
var cursor = objectStore.openCursor();
cursor.onsuccess = function (e) {
var res = e.target.result;
if (res) {
res.advance(25);
res.continue();
console.log(res.value);
}
}
}
最佳答案
res.advance(25) 将跳过 25 行,但仍会加载其余行。我更改了你的代码+添加了一些评论。您可能想使用这样的东西:
var openRequest = indexedDB.open("USA", 1);
openRequest.onsuccess = function (e) {
var db = e.target.result;
var transaction = db.transaction(["Male"], "readonly");
var objectStore = transaction.objectStore("Male");
var cursor = objectStore.openCursor();
var results = null; // variable to store the results
var startIndex = 25,
maxResults = 25;
cursor.onsuccess = function (e) {
var res = e.target.result;
if (res) {
if (!results) {
results = [];
// skip rows, but only the first time
res.advance(startIndex);
} else {
results.push(res.value)
// We don't have 25 results yet, continue to load a next one
if(results.length < maxResults) {
res.continue();
}
}
}
}
transaction.oncomplete = function() {
// maxResults loaded or maybe it was the last page so it might not be full
console.log(results);
}
}
下面的示例要简单得多,并且可以使用自动增量,但只有在未删除结果时页面才会满(不是完整的代码,但都是关于 IDBKeyRange.bound(0, 25) 的)
var cursor = objectStore.openCursor(IDBKeyRange.bound(0, 25));
var results = [];
cursor.onsuccess = function (e) {
var res = e.target.result;
if (res) {
results.push(res.value)
}
}
transaction.oncomplete = function() {
console.log(results);
}
关于javascript - 从indexeddb分段加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25416507/