2013-10-26 33 views
1

我想創建一個基本上需要使用IndexedDB存儲一些數據的Firefox OS的應用程序。IndexedDB參考錯誤:數據庫未定義

當用戶點擊一個提交按鈕時會調用store()函數,這會導致用戶提交表單的名稱和描述變量的創建。

但是,我不斷收到一個參考錯誤,說我的數據庫對象沒有定義。任何想法爲什麼發生這種情況?

這裏是我當前的代碼: -

function store() { 
    // create the transaction with 1st parameter is the list of stores and the second specifies 
    // a flag for the readwrite option 
    var transaction = db.transaction([ 'Apps' ], 'readwrite'); 

    //Create the Object to be saved i.e. our App details 
    var value = {}; 
    value.name = name; 
    value.desc = description; 

    // add the details to the store 
    var store = transaction.objectStore('Apps'); 
    var request = store.add(value); 
    request.onsuccess = function (e) { 
     alert("Your App data has been saved"); 
    }; 
    request.onerror = function (e) { 
     alert("Error in saving the App data. Reason : " + e.value); 
    } 
} 


$(document).ready(function(){ 
// variable which will hold the database connection 
var db; 

    if (window.indexedDB) { 
     console.log("IndexedDB is supported"); 
    } 
    else { 
     alert("Indexed DB is not supported!"); 
    } 

    // open the database 
    // 1st parameter : Database name. We are using the name 'Appsdb' 
    // 2nd parameter is the version of the database. 
    var request = indexedDB.open('Appsdb', 1); 

    request.onsuccess = function (e) { 
     // e.target.result has the connection to the database 
     db = e.target.result; 

     console.log(db); 
     console.log("DB Opened!"); 
    } 

    request.onerror = function (e) { 
     console.log(e); 
    }; 

    // this will fire when the version of the database changes 
    // We can only create Object stores in a versionchange transaction. 
    request.onupgradeneeded = function (e) { 
     // e.target.result holds the connection to database 
     db = e.target.result; 

     if (db.objectStoreNames.contains("Apps")) { 
      db.deleteObjectStore("Apps"); 
     } 

     // create a store named 'Apps' 
     // 1st parameter is the store name 
     // 2nd parameter is the key field that we can specify here. Here we have opted for autoIncrement but it could be your 
     // own provided value also. 
     var objectStore = db.createObjectStore('Apps', { keyPath: 'id', autoIncrement: true }); 

     console.log("Object Store has been created"); 
    }; 

}); 
+0

您是否在Index中支持IndexedDB? –

回答

4

問題在於db變量的範圍。目前,您在$(document).ready函數中聲明瞭以下行var db;。將其聲明移到更全局的範圍,即在此函數之外,變量也將在store()函數中可見。

希望這會有所幫助。

+0

謝謝。這工作!我正在試驗來自你的博客的例子,並混合了變量作用域。 :-) – Sayak

2
var value = {}; 
value.name = name; 
value.desc = description; 

值分配給的名稱和說明。 name = formname.name.value description = formname.description.value

+0

這是我之前做過的,但是,問題在於db變量的範圍。 – Sayak