我必须承认我对indexedDB很新
我编写了一个简单的indexedDB代码,如下所示:
function go(){var req = window.indexedDB.open("Uploader",1),db; req.onerror=function(e){console.log('Error')}; req.onsuccess = function(e){db=e.target.result;}; req.onupgradeneeded = function(e){console.log(db); db=e.target.result;db=e.target.result; var os = db.createObjectStore('Files',{keyPath:"files"}); os.createIndex('text','text_file',{unique:false}) var trans = db.transaction(['text'],"readwrite"); var objectstore= trans.objectStore("text"); var addreq = objectstore.add('Instructions.js'); addreq.onsuccess = function(e){console.log('Success!');console.dir(e)} }}
它给我的错误是Uncaught InvalidStateError:无法在’IDBDatabase’上执行’transaction’:版本更改事务正在运行.
这是说版本更改事务正在运行,但据我所研究,版本更改事务是从IDBFactory.open方法,我没有使用,我已经指定此事务是readwrite和此事务处于onupgradeneeded那为什么会有错误?
我必须承认我对indexedDB很新
解决方法
versionchange事务还允许您读写.您只需要在onupgradeneeded函数中访问为您创建的事务.
function go() { var req = indexeddb.open(...); req.onupgradeneeded = function(event) { var db = event.target.result; var os = ... var transaction = event.target.transaction;// the important part var addRequest = transaction.objectStore('').index('').add('value'); addRequest.onsuccess = function() {console.log('Success!');}; }; }
您遇到错误,因为您在版本更改事务仍在运行时尝试启动第二个事务.