HTML5离线存储无法正常工作

时间:2013-03-26 19:36:29

标签: html5 local-storage offline-caching

这是W3C离线网络存储示例提供的代码:http://www.w3.org/TR/offline-webapps/

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" charset="utf-8">
        function renderNote(row) {
          console.log(row);
        }
        function reportError(source, message) {
          console.log("err");
        }

        function renderNotes() {
          db.transaction(function(tx) {
            tx.executeSql('CREATE TABLE IF NOT EXISTS Notes(title TEXT, body TEXT)', 
              []);
            tx.executeSql('SELECT * FROM Notes', [], function(tx, rs) {
              for(var i = 0; i < rs.rows.length; i++) {
                renderNote(rs.rows[i]);
              }
            });
          });
        }

        function insertNote(title, text) {
          db.transaction(function(tx) {
            tx.executeSql('INSERT INTO Notes VALUES(?, ?)', [ title, text ],
              function(tx, rs) {
                // …
              },
              function(tx, error) {
                reportError('sql', error.message);
              });
          });
        }
    </script>
  </head>
  <body>
  </body>
</html>

根本没有控制台日志输出。怎么了?

2 个答案:

答案 0 :(得分:1)

缺少db的实例化和函数的执行。

检查此JSfiddle:http://jsfiddle.net/Ax5d7/4/

<强>的JavaScript

var db = openDatabase("notes", "", "The Example Notes App!", 1048576);

function renderNote(row) {
    console.log(row);
}

function reportError(source, message) {
    console.log("err");
}

function renderNotes() {
    db.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS Notes(title TEXT, body TEXT)', 
        []);

        tx.executeSql('SELECT * FROM Notes', [], function(tx, rs) {
            for(var i = 0; i < rs.rows.length; i++) {
                renderNote(rs.rows[i]);
            }
        });
    });
}

function insertNote(title, text) {
    db.transaction(function(tx) {
        tx.executeSql('INSERT INTO Notes VALUES(?, ?)', [ title, text ],
        function(tx, rs) {
            // …
        },
        function(tx, error) {
            reportError('sql', error.message);
        });
    });
}

renderNotes();

更简单

var db = openDatabase("notes", "", "The Example Notes App!", 10000);

db.transaction(function(t) {
    //t.executeSql("DROP TABLE Notes");
    t.executeSql("CREATE TABLE IF NOT EXISTS Notes(title TEXT, body TEXT)");
    t.executeSql("INSERT INTO Notes VALUES(?, ?)", [ 'title', 'content' ]);
});

答案 1 :(得分:0)

请注意,http://www.w3.org/TR/webdatabase/已不再维护,未来版本可能会删除支持。

http://www.w3.org/TR/webstorage/#storage是要走的路......

有关浏览器支持表,请参阅caniuse.com。