Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

javascript - Why is db.transaction not working with indexeddb?

I am new at using inxededdb and am trying to get data out of a store. The store contains data, but for some reason the code stops after trying to set the var tx. If I am missing anything please let me know. Here is the function with which I am trying to get the book:

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);
      }
    };
}

Solved Version:

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);
    };      
  };
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is probably your db variable. You are probably accessing a closed or null instance of a connection object.

Try instead to create the db connection right inside the function. Do NOT use a global db variable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...