gpt4 book ai didi

javascript - IndexedDB 引用错误 : db is not defined

转载 作者:行者123 更新时间:2023-11-30 07:40:11 26 4
gpt4 key购买 nike

我正在尝试为 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");
};

});

最佳答案

问题在于 db 变量的范围。当前,您在 $(document).ready 函数中声明了以下行 var db;。将其声明移至更全局的范围,即在此函数之外,并且该变量也将在 store() 函数中可见。

希望这对您有所帮助。

关于javascript - IndexedDB 引用错误 : db is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19609173/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com