为什么db.transaction无法与indexeddb一起使用?

way*_*yzz 4 html php jquery indexeddb

我是使用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 $_GET['book'] ?>);

        requesttrans.onerror = function(event) {

        };

        requesttrans.onsuccess = function(event) {
            alert(requesttrans.result.text);
        };

    };
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*osh 5

问题可能出在您的db变量上。您可能正在访问连接对象的封闭或空实例。

尝试改为在函数内部创建数据库连接。不要使用全局db变量。