2

基本的にIndexedDBを使用してデータを保存する必要があるFirefox OS用のアプリケーションを作成しようとしています。

store() 関数は、ユーザーが送信ボタンをクリックすると呼び出され、その結果、ユーザーが送信したフォームの name 変数と description 変数が作成されます。

ただし、db オブジェクトが定義されていないという参照エラーが発生し続けます。なぜこれが起こっているのですか?

これが私の現在のコードです:-

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

});
4

2 に答える 2

5

問題は、db変数のスコープにあります。現在var db;、関数内で次の行が宣言されてい$(document).readyます。宣言をよりグローバルなスコープ、つまりこの関数の外に移動すると、変数はstore()関数内でも表示されます。

お役に立てれば。

于 2013-10-27T04:17:33.757 に答える
2
var value = {};
value.name = name;
value.desc = description;

名前と説明に値を割り当てます。name=フォーム名.name.value 説明=フォーム名.description.value

于 2013-10-26T17:38:00.383 に答える