我试图保存一个 key ,如果它不存在,如果存在 - 只需读取它。
但它总是提示未定义
。
var idb = window.indexedDB.open('MyDB', 1);
idb.onupgradeneeded = function(e)
{
var db = e.target.result;
if (!db.objectStoreNames.contains('all'))
{
db.createObjectStore('all');
}
}
idb.onsuccess = function(e)
{
db = e.target.result;
setData();
}
function setData()
{
var store = db.transaction(['all'], 'readwrite').objectStore('all');
var item1 = {theTitle: 'myKey', theValue: 'myValue'};
var op = store.get('myKey');
op.onsuccess = function(event)
{
alert(op.result);
}
op.onerror = function()
{
var req = store.add(item1, 1);
req.onsuccess = function()
{
alert('Saved');
}
}
}
最佳答案
如果找不到任何内容,IDBObjectStore 将返回 undefined,因此您的 op.onsuccess 函数实际上工作正常。
请参见此处:http://www.w3.org/TR/IndexedDB/#widl-IDBObjectStore-get-IDBRequest-any-key
您可以将“store.add”代码放入 onsuccess 函数中:
var transaction = db.transaction(['all'], 'readwrite');
var store = transaction.objectStore('all');
var item1 = {
theTitle: 'myKey',
theValue: 'myValue'
};
var op = store.get('myKey');
op.onsuccess = function(event) {
if (op.result) {
alert(op.result);
} else {
var req = store.add(item1, 1);
req.onsuccess = function() {
alert('Saved');
}
}
}
transaction.oncomplete = function(event) {
console.log("Transaction complete. Everything is saved.")
}
还要查看 transaction.complete、onerror 和 onabort 函数 - 它们为您提供了一个更好的位置来转储所有错误处理。
我建议您阅读 IDB 规范:乍一看似乎很冗长,但您会习惯它,并且它是 IDB 上最好的文档。
http://www.w3.org/TR/IndexedDB/
玩得开心!
关于javascript - IndexedDB如何读取元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29797869/