查找indexedDB中是否已存在值

时间:2012-07-18 19:39:32

标签: exists indexeddb

我在IndexedDB工作。我能够在我的jquery移动应用程序中创建,填充和删除值。

现在,当我第一次来到一个页面时,我应该检查我的数据库中是否有值。如果是这样,我需要显示“存在”或“不存在”,如果它不存在。我写了下面的代码。我在document.ready上调用了这个函数。

myapp.indexedDB.existsInFavourites = function(value){
    var db = myapp.indexedDB.db;
    var request = db.transaction(["todo"]).objectStore("todo").get(typeid);
    request.onerror = function(event) {
      // Handle errors!
    };
    request.onsuccess = function(event) {
      // Do something with the request.result!

    };
  }

导致我出现以下错误

Uncaught TypeError : Cannot call method 'transaction' of null

任何建议都会有很大的帮助。在此先感谢!!!

1 个答案:

答案 0 :(得分:0)

问题看起来与线路有关:

var db = myapp.indexedDB.db;

您需要连接到数据库,然后在回调中完成工作。简而言之,如:

// var typeid = ...;

// Request a connection
var openRequest = indexedDB.open(name,version);
var openRequest.onsuccess = function(event) {
    var db = event.target.result;
    // event.target === this and event.target === openRequest
    // so use whatever you prefer

    // Now use the 'db' variable to do the work
    // Note: removed unnecessary brackets around todo
    var getRequest = db.transaction("todo").objectStore("todo").get(typeid);
    getRequest.onsuccess = function(event) {
        var myResult = event.target.value;
        // event.target === this, and event.target === getRequest

        console.log('Got %s !', myResult);
    }
}