有很多这样的错误发生。只有这篇文章http://dev.opera.com/articles/introduction-to-indexeddb/说明了原因-----“使用 IndexedDB,我们数据库上的每个操作或事务都必须发生在回调函数。”
这是我的简单示例,请使用 chrome 的 devtool->resource->indexedDB 进行检查;(如果 indexedDB 中没有任何内容,请尝试刷新浏览器)
html部分:
<form id="form1">
<label for="task">What do you need to do?</label>
<input type="text" name="task" id="task" value="" required>
<button type="submit" id="submit">Save entry</button>
</form>
脚本部分:
var idb = indexedDB.open('niangzi10', 2);
var dbobject; // Define a global variable to hold our database object
idb.onsuccess = function (evt) {
console.log("success");
if (dbobject === undefined) {
dbobject = evt.target.result;
}
}
idb.onupgradeneeded = function (evt) {
dbobject = evt.target.result;
if (evt.oldVersion < 1) {
dbobject.createObjectStore('tasks', { autoIncrement: true });
}
}
//transaction operation in callback function
var form1 = document.getElementById('form1');
form1.addEventListener('submit', function (evt) {
'use strict';
evt.preventDefault();
var entry = {}, transaction, objectstore, request;
entry = { name: document.querySelector("#task").value };
// Open a transaction for writing
transaction = dbobject.transaction(['tasks'], 'readwrite');
objectstore = transaction.objectStore('tasks');
// Save the entry object
request = objectstore.add(entry);
transaction.oncomplete = function (evt) {
alert("'" + document.querySelector("#task").value + "'has been insert into indexedDB;please check it using chrome's devtool->resource->indexedDB(if nothing,refresh browser);");
};
});