我正在使用IndexDB
创建一个用户对象存储库,但是在尝试添加用户时,我在var request = db.transaction(['person'], 'readwrite')
行上收到一个错误。
给出的错误为:
“未捕获的类型错误:无法在test.js:45中读取add(test.js:32)时未定义的属性'transaction'”
我的脚本如下所示:
var request = window.indexedDB.open("connectDB", 1);
request.onerror = function (event)
{
console.log('The database is opened failed');
};
var db;
request.onsuccess = function (event)
{
db = request.result;
console.log('The database is opened successfully');
};
var db;
request.onupgradeneeded = function (event)
{
db = event.target.result;
var objectStore;
if (!db.objectStoreNames.contains('users'))
{
objectStore = db.createObjectStore('users', { keyPath: 'id' });
objectStore.createIndex('name', 'name', { unique: false });
objectStore.createIndex('email', 'email', { unique: true });
}
}
function add()
{
var request = db.transaction(['person'], 'readwrite')
.objectStore('person')
.add({ id: 1, name: 'Jam', age: 24, email: 'jam@example.com' });
request.onsuccess = function (event) {
console.log('The data has been written successfully');
};
request.onerror = function (event) {
console.log('The data has been written failed');
}
}
add();
任何帮助都将不胜感激
1条答案
按热度按时间ttcibm8c1#
看起来您试图在未初始化
add()
的调用过程中访问db
(请注意,执行脚本时会立即调用add()
)。但是,只有成功创建数据库连接后,才会初始化
db
变量:有很多方法可以解决这个问题,尽管最简单的方法是将对
add()
的调用移到onsuccess
处理程序中,如下所示:最后,我注意到您声明了两个
var db;
变量--考虑删除其中一个。希望这对您有所帮助!