无法读取未定义的IndexedDB的属性'transaction'

mwecs4sa  于 2022-12-09  发布在  IndexedDB
关注(0)|答案(1)|浏览(355)

我正在使用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();

任何帮助都将不胜感激

ttcibm8c

ttcibm8c1#

看起来您试图在未初始化add()的调用过程中访问db(请注意,执行脚本时会立即调用add())。
但是,只有成功创建数据库连接后,才会初始化db变量:

request.onsuccess = function (event) 
{
    db = request.result;
    console.log('The database is opened successfully');

    // It is now safe to interact with the database
};

有很多方法可以解决这个问题,尽管最简单的方法是将对add()的调用移到onsuccess处理程序中,如下所示:

request.onsuccess = function (event) 
{
    db = request.result;
    console.log('The database is opened successfully');

    add(); // Add this
};

// add(); <-- remove this from the end of your script

最后,我注意到您声明了两个var db;变量--考虑删除其中一个。希望这对您有所帮助!

相关问题