我一直在使用IndexedDB,我可以成功创建一个新数据库,创建一个商店,并在"需要升级时"添加一个值.我不明白的是,数据库是否保持"开放"状态,还是必须在需要访问数据库中读/写信息的每个函数内重新打开它?
例如,这是我的代码(可以工作)来创建一个新数据库,并插入一条记录:
$(document).ready(function() {
var db;
function initDB() {
console.log("opening db...");
var req = indexedDB.open(dbName, version);
req.onsuccess = function(event) {
db = this.result;
console.log("opening db is done");
}
req.onerror = function(event) {
console.log("error opening db: ", event.target.errorCode);
}
req.onupgradeneeded = function(event) {
db = event.target.result;
var store = db.createObjectStore("creds", { autoincrement: true });
store.add({ username:'none', password:'none'}, 1);
}
}
Run Code Online (Sandbox Code Playgroud)
造成我混淆的是,当我需要访问该数据库中的记录,或添加更多记录或删除记录时,我想我可以创建一个新函数并插入一些值.这就是我所拥有的(失败):
function saveCreds() {
usr = $("#username").val();
psw = $("#password").val();
$.getJSON(baseURL + "cred-check/?callback=?", { username:usr, password:psw }, function(data) {
if (data.creds_good …Run Code Online (Sandbox Code Playgroud) 我是使用inxededdb的新手,正在尝试从存储中获取数据。存储中包含数据,但是由于某些原因,代码在尝试设置var tx之后停止。如果我有任何遗漏,请告诉我。这是我尝试获取该书的功能:
function getBook(){
var tx = db.transaction("book", "readonly");
var store = tx.objectStore("book");
var index = store.index("by_getid");
var request = index.get("<?php echo $_GET['book'] ?>");
request.onsuccess = function() {
var matching = request.result;
if (matching !== undefined) {
document.getElementById("text-container").innerHTML = matching.text;
} else {
alert('no match');
report(null);
}
};
}
Run Code Online (Sandbox Code Playgroud)
解决的版本:
function getBook(){
var db;
var request = indexedDB.open("library", 1);
request.onsuccess = function (evt) {
db = request.result;
var transaction = db.transaction(["book"]);
var objectStore = transaction.objectStore("book");
var requesttrans = objectStore.get(<?php echo …Run Code Online (Sandbox Code Playgroud)