-1

我正在阅读面向 Web 开发人员的专业 JavaScript 第 3 版并尝试示例。第23章有一个demo: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);
            };
        }
    }

})();
4

2 回答 2

0

我建议您阅读一些有关该主题的博客。正如 Josh Froelich 所说,您的工作方式已被弃用。我写了一些关于它的博客,我建议你在继续使用 indexeddb API 之前先阅读它们。

于 2013-07-02T17:10:03.057 回答
0
  • 不推荐使用 setVersion
  • 版本是整数,而不是字符串(而不是浮点数)
  • 在你的范围内使用数据库变量并不能保证它的状态,你应该只在回调中使用它
  • 您只能在 onupgradeneeded 回调中使用的事务上下文中修改您的架构。
于 2013-07-02T15:14:12.690 回答