简体   繁体   中英

IndexedDB how to read element?

I am trying to save a key if it doesn't exists and if it does- just read it. But it always alerts undefined .

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 will return undefined if it can't find anything, so your op.onsuccess function is actually working correctly.

See here: http://www.w3.org/TR/IndexedDB/#widl-IDBObjectStore-get-IDBRequest-any-key

You can place your "store.add" code in your onsuccess function:

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.")
}

Also look at the transaction.complete, onerror and onabort functions - they provide you with a better place to do dump all your error handling.

I would advise you to read the IDB spec: it's seems longwinded at first, but you get used to it and it's the best document there is on IDB.

http://www.w3.org/TR/IndexedDB/

Have fun!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM