0

这是 W3C 示例为离线 Web 存储提供的代码: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>

根本没有控制台日志输出。有什么事?

4

2 回答 2

1

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

检查这个 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' ]);
});
于 2013-03-26T19:43:59.233 回答
0

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

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

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

于 2013-03-26T21:12:28.093 回答