0

我有一个现有的数据库。我正在尝试使用 indexedDB 从数据库中检索数据,但我无法从数据库中获取数据。

 var data = [];
    // creating or opening the database
    var db;
    var request = window.indexedDB.open("database");

    request.onerror = function(event) {
      console.log("error: ");
    };

    request.onsuccess = function(event) {
      db = request.result;
      console.log("success: "+ db);
    };

    request.onupgradeneeded = function(event) {
         var db = event.target.result;
         var objectStore = db.createObjectStore("Subject", {keyPath: "id"});
         for (var i in data) {
                 objectStore.add(data[i]);       
         }
    }


function readAll() {
    var objectStore = db.transaction("Subject").objectStore("Subject");
    console.log(objectStore);
    objectStore.openCursor().onsuccess = function(event) {
      var cursor = event.target.result;
      if (cursor) {
            alert("Name for id " + cursor.key + " is " + cursor.value.Subject);
            cursor.continue();
      }
      else {
            alert("No more entries!");
      }
    };      
}

提前致谢。

4

2 回答 2

1

你很接近。

var data = [];

我假设您实际上在某处有一些数据,并且它确实具有 id 属性,因为您将其指定为索引键,例如

var data = [{id: 'foo' }, { id: 'bar' } ];

现在在这里:

var objectStore = db.createObjectStore("Subject", {keyPath: "id"});
for (var i in data) {
        objectStore.add(data[i]);       
}

小心for..in数组)

我认为您实际上并没有在此处添加任何数据,这是您无法阅读它的原因之一。要将数据添加到对象存储,请首先尝试创建读/写事务,然后获取对对象存储的引用并添加对象。

var trans = db.transaction(["Subject"], "readwrite").objectStore("Subject");

请注意将数组用作第一个参数,将transaction()“readwrite”用作第二个参数。(一些例子使用了IDBTransaction.READ_WRITE常量,但这似乎不适用于最新版本的 Webkit。)

var objectStore = db.transaction("Subject").objectStore("Subject");

试试这个:

var trans = db.transaction( [ "Subject" ] );
  , objectStore = trans.objectStore( "Subject" );
objectStore.openCursor( IDBKeyRange.lowerBound(0) ).onsuccess = function(event) {..}
于 2013-10-02T00:19:09.093 回答
0

我确实遇到过同样的错误。它发生是因为有时甚至在返回结果数据之前就执行了 onSuccess。所以你应该检查结果数据是否为空。

要解决此问题,请尝试使用 oncomplete 而不是 onSuccess 并使用 Jquery indexedDB 插件。该插件需要更改某些代码,但具有更一致的 indexedDB 实现。见http://nparashuram.com/jquery-indexeddb/

于 2014-08-24T09:52:31.253 回答