當你嘗試從result里面想獲取出數據并且另外賦值,請記住,IDB是一個異步asyn的數據交互方式,你每次處理都要在一個回執里面進行才行。 錯誤示范:
var transaction = db.transaction('myQuestionaire','readwrite');var store = transaction.objectStore('myQuestionaire');var IDB = store.get(that.requestInfo);正確示范:
var transaction = db.transaction('myQuestionaire','readwrite');var store = transaction.objectStore('myQuestionaire');var request = store.get(that.requestInfo);request.onsuccess = function(){ console.log(request.result)//完全可以訪問,還能操作}Uncaught InvalidStateError: Failed to read the ‘result’ PRoperty from ‘IDBRequest’: The request has not finished
參考原文
這個時候你可能沒懂各個教程里面的各種var
聲明,一定要注意作用域的問題。
You need to learn about how to write asynchronous javascript. Your db variable isn’t defined at the time you access it.
錯誤示范:
var r = indexedDB.open();var db = null;r.onsuccess = function(event) { db = event.target.result); }正確示范:
var r = indexedDB.open();r.onsuccess = function(event) { var db = event.target.result;};that means db isn’t available outside the scope of the onsuccess function. Stop trying to use it outside its scope or you will just run into the problem you are experiencing.
failed to execute ‘put’ on ‘idbobjectstore’ evaluating the object store’s key path did not yield a value
參考原文
儲存數據的時候必須要帶上object store的key一起儲存,或者使用一個key generator({autoIncrement: true})
例如:
Uncaught InvalidStateError: Failed to execute ‘transaction’ on ‘IDBDatabase’: A version change transaction is running
參考原文
The versionchange transaction also allows you to readwrite. You just need to access the transaction created for you within the onupgradeneeded function.
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!');}; };}You are encountering the error because you are trying to start a second transaction while the version change transaction is still running.
這個時候聯系到的知識點就時versionchange,這種狀態的改變在IDB里面要放到打開數據庫的回執的onupgradeneeded函數里面。針對onunpgradeneeded的介紹,摘抄了百度知道里面一個回答,看了就懂了。
IDBOpenDBRequest還有一個類似回調函數句柄——onupgradeneeded。 該句柄在我們請求打開的數據庫的版本號和已經存在的數據庫版本號不一致的時候調用。
indexedDB.open方法還有第二個可選參數,數據庫版本號,數據庫創建的時候默認版本號為1,當我們傳入的版本號和數據庫當前版本號不一致的時候onupgradeneeded就會被調用,當然我們不能試圖打開比當前數據庫版本低的version.
代碼中定義了一個myDB對象,在創建indexedDB request的成功毀掉函數中,把request獲取的DB對象賦值給了myDB的db屬性,這樣就可以使用myDB.db來訪問創建的indexedDB了。
用indexedBD的時候要善用onerror來獲取錯誤的信息,這樣就知道哪里出錯了。
參考之前寫過的一篇文章——【Hours】使用indexedDB中遇到的問題。
新聞熱點
疑難解答