Fon*_*hau 22 javascript indexeddb
好的,首先,对不起我的英语.
我在一个web项目中工作,显示当我在输入框中键入内容时,但我想使用IndexedDB来提高Firefox中的查询速度.
使用WebSQL我有这句话:
db.transaction(function (tx) {
var SQL = 'SELECT "column1",
"column2"
FROM "table"
WHERE "column1" LIKE ?
ORDER BY "sortcolumn" DESC
LIMIT 6';
tx.executeSql(SQL, [searchTerm + '%'], function(tx, rs) {
// Process code here
});
});
Run Code Online (Sandbox Code Playgroud)
我想用IndexedDB做同样的事情,我有这个代码:
db.transaction(['table'], 'readonly')
.objectStore('table')
.index('sortcolumn')
.openCursor(null, 'prev')
.onsuccess = function (e) {
e || (e = event);
var cursor = e.target.result;
if (cursor) {
if (cursor.value.column1.substr(0, searchTerm.length) == searchTerm) {
// Process code here
} else {
cursor.continue();
}
}
};
Run Code Online (Sandbox Code Playgroud)
但是速度太慢而且我的代码有问题......我想知道有没有更好的方法来做到这一点.
谢谢回复.
Fon*_*hau 23
我终于找到了解决这个问题的方法.
解决方案包括在搜索词和搜索词之间绑定一个键范围,在结尾处加上'z'字母.例:
db.transaction(['table'], 'readonly')
.objectStore('table')
.openCursor(
IDBKeyRange.bound(searchTerm, searchTerm + '\uffff'), // The important part, thank Velmont to point out
'prev')
.onsuccess = function (e) {
e || (e = event);
var cursor = e.target.result;
if (cursor) {
// console.log(cursor.value.column1 + ' = ' + cursor.value.column2);
cursor.continue();
}
};
Run Code Online (Sandbox Code Playgroud)
因为我需要对结果进行排序,所以我在事务之前定义了一个数组,然后在加载所有数据时调用它,如下所示:
var result = [];
db.transaction(['table'], 'readonly')
.objectStore('table')
.openCursor(
IDBKeyRange.bound(searchTerm, searchTerm + '\uffff'), // The important part, thank Velmont to point out
'prev')
.onsuccess = function (e) {
e || (e = event);
var cursor = e.target.result;
if (cursor) {
result.push([cursor.value.column1, cursor.value.sortcolumn]);
cursor.continue();
} else {
if (result.length) {
result.sort(function (a, b) {
return a[1] - b[2];
});
}
// Process code here
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7343 次 |
| 最近记录: |