當你嘗試從result里面想獲取出數(shù)據(jù)并且另外賦值,請記住,IDB是一個異步asyn的數(shù)據(jù)交互方式,你每次處理都要在一個回執(zhí)里面進行才行。 錯誤示范:
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
參考原文
儲存數(shù)據(jù)的時候必須要帶上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.
這個時候聯(lián)系到的知識點就時versionchange,這種狀態(tài)的改變在IDB里面要放到打開數(shù)據(jù)庫的回執(zhí)的onupgradeneeded函數(shù)里面。針對onunpgradeneeded的介紹,摘抄了百度知道里面一個回答,看了就懂了。
IDBOpenDBRequest還有一個類似回調(diào)函數(shù)句柄——onupgradeneeded。 該句柄在我們請求打開的數(shù)據(jù)庫的版本號和已經(jīng)存在的數(shù)據(jù)庫版本號不一致的時候調(diào)用。
indexedDB.open方法還有第二個可選參數(shù),數(shù)據(jù)庫版本號,數(shù)據(jù)庫創(chuàng)建的時候默認版本號為1,當我們傳入的版本號和數(shù)據(jù)庫當前版本號不一致的時候onupgradeneeded就會被調(diào)用,當然我們不能試圖打開比當前數(shù)據(jù)庫版本低的version.
代碼中定義了一個myDB對象,在創(chuàng)建indexedDB request的成功毀掉函數(shù)中,把request獲取的DB對象賦值給了myDB的db屬性,這樣就可以使用myDB.db來訪問創(chuàng)建的indexedDB了。
用indexedBD的時候要善用onerror來獲取錯誤的信息,這樣就知道哪里出錯了。
參考之前寫過的一篇文章——【Hours】使用indexedDB中遇到的問題。
新聞熱點
疑難解答