indexedDB中的DOM IDBDatabase异常8

时间:2013-07-02 10:46:32

标签: indexeddb

我正在阅读针对Web开发人员的专业JavaScript第3版和尝试示例。 在第23章中,有一个演示:IndexedDBExample02.htm。它有一个错误:DOM IDBDatabase Exception 8请帮助,非常感谢!

(function(){

    var indexedDB = window.indexedDB || window.msIndexedDB || window.mozIndexedDB || window.webkitIndexedDB,
        request,
        store,
        database,
        users = [
            {
                username: "007",
                firstName: "James",
                lastName: "Bond",
                password: "foo"
            },
            {
                username: "ace",
                firstName: "John",
                lastName: "Smith",
                password: "bar"
            }                
        ];

    request = indexedDB.open("example");
    request.onerror = function(event){
        alert("Something bad happened while trying to open: " + event.target.errorCode);
    };
    request.onsuccess = function(event){
        database = event.target.result;
        initializeDatabase();
    };    

    function initializeDatabase(){
        if (database.version != "1.0"){
            request = database.setVersion("1.0");
            request.onerror = function(event){
                alert("Something bad happened while trying to set version: " + event.target.errorCode);
            };
            request.onsuccess = function(event){
                store = database.createObjectStore("users", { keyPath: "username" });
                var i=0,
                    len = users.length;

                while(i < len){
                    store.add(users[i++]);
                }

                alert("Database initialized for first time. Database name: " + database.name + ", Version: " + database.version);
            };
        } else {
            alert("Database already initialized. Database name: " + database.name + ", Version: " + database.version);

            request = database.transaction("users").objectStore("users").get("007");
            request.onsuccess = function(event){
                alert(event.target.result.firstName);
            };
        }
    }

})();

2 个答案:

答案 0 :(得分:0)

  • 不推荐使用setVersion
  • 版本是整数,而不是字符串(而不是浮点数)
  • 在您的范围内使用数据库变量并不保证其状态,您应该只在回调中使用它
  • 您只能在onupgradeneeded回调中使用的事务的上下文中修改您的架构。

答案 1 :(得分:0)

我建议你阅读一些关于这个主题的博客。 Josh Froelich提到,你的工作方式已被弃用。我写了一些关于它的blogs,我建议你在继续使用indexeddb API之前先阅读它们。