Web | indexedDB的常见错误总结
关于transaction的错误代码let db;window.onload = function() {// Open our database; it is created if it doesn't already exist// (see onupgradeneeded below)let request = window.indexedDB.open('notes', 1)...
·
关于transaction的错误
代码
let db;
window.onload = function() {
// Open our database; it is created if it doesn't already exist
// (see onupgradeneeded below)
let request = window.indexedDB.open('notes', 1);
// onerror handler signifies that the database didn't open successfully
request.onerror = function() {
console.log('Database failed to open');
};
// onsuccess handler signifies that the database opened successfully
request.onsuccess = function() {
console.log('Database opened successfully');
// Store the opened database object in the db variable. This is used a lot below
db = request.result;
// Run the displayData() function to display the notes already in the IDB
displayData();
};
// Setup the database tables if this has not already been done
request.onupgradeneeded = function(e) {
// Grab a reference to the opened database
let db = e.target.result;
// Create an objectStore to store our notes in (basically like a single table)
// including a auto-incrementing key
let objectStore = db.createObjectStore('notes', { keyPath: 'id', autoIncrement:true });
// Define what data items the objectStore will contain
objectStore.createIndex('title', 'title', { unique: false });
objectStore.createIndex('body', 'body', { unique: false });
console.log('Database setup complete');
};
// Create an onsubmit handler so that when the form is submitted the addData() function is run
form.onsubmit = addData;
// Define the addData() function
function addData(e) {
...
// open a read/write db transaction, ready for adding the data
let transaction = db.transaction(['notes'], 'readwrite');
...
}
};
运行结果
Failed to exectue ‘transaction’ on ‘IDBDatabase’: One of the specified stores was not found.
错误原因
当为open方法传入一个本域没有的数据库名时,会创建相应的数据库,并触发success、upgradeneeded事件,从而创建一个objectStore。但是,chrome54并不会触发upgradeneeded事件,造成objectStoret不会被创建,后续在objectStore上创建事务并操作数据时候就会报错。解决办法是,在open方法传入第二个参数(与已有version不同,且更大,通常是在原有的基础上加一),上面的例子中把open的第二个参数改成2即可,这样就会触发chrome上的upgradeneeded事件了。
更多推荐



所有评论(0)