使用WebSQL输入数据

时间:2016-02-06 21:10:03

标签: javascript google-chrome-extension web-sql

我在使用WebSQL进行Chrome扩展时遇到了一些问题。 (这是我第一次使用它) 我找到了本教程,并尝试根据自己的需要进行调整:http://www.html5rocks.com/en/tutorials/webdatabase/todo/

继承我的代码:

var favourites = {};
favourites.webdb = {};

favourites.webdb.db = null;

favourites.webdb.open = function () {
  var dbSize = 5 * 1024 * 1024; // 5MB
  favourites.webdb.db = openDatabase("favourites", "1", "Favourites Database", dbSize);
};

favourites.webdb.onError = function(tx, e) {
  alert("There has been an error: " + e.message);
};

favourites.webdb.onSuccess = function(tx, r) {
  // re-render the data.
  // loadTodoItems is defined in Step 4a
  favourites.webdb.getAllTiles(loadTiles);
};


favourites.webdb.createTable = function() {
  var db = favourites.webdb.db;
  db.transaction(function(tx) {
    tx.executeSql("CREATE TABLE IF NOT EXISTS " +
                  "tiles(ID INTEGER PRIMARY KEY ASC, name, colour, width, linkURL, imgURL)", []);
  });
};


favourites.webdb.addTile = function(tileName, tileColour, tileWidth, tileLinkURL, tileImgURL) {
  var db = favourites.webdb.db;
  db.transaction(function(tx){
    tx.executeSql("INSERT INTO tiles(name, colour, width, linkURL, imgURL) VALUES (?,?,?,?,?)",
        [tileName, tileColour, tileWidth, tileLinkURL, tileImgURL],
        favourites.webdb.onSuccess,
        favourites.webdb.onError);
   });
};

function loadTiles(tx, rs) {
  var rowOutput = "";
  var todoItems = document.getElementById("tiles");
  for (var i=0; i < rs.rows.length; i++) {
    rowOutput += renderTile(rs.rows.item(i));
  }

  tiles.innerHTML = rowOutput;
}
function renderTile(row) {
  return "<a href='" + row.tileLinkURL + "'>" +
      "<div class='mdl-js-button mdl-js-ripple-effect tile' style='background-color:" + row.tileColour + "; width:" + row.tileWidth + "px;'>" +
      "<img class='tileimg' src='" + row.tileImgURL + "'>" +
      "</div>" +
      "</a>";
};


favourites.webdb.deleteTile = function(id) {
  var db = favourites.webdb.db;
  db.transaction(function(tx){
    tx.executeSql("DELETE FROM tiles WHERE ID=?", [id],
        favourites.webdb.onSuccess,
        favourites.webdb.onError);
    });
};


function init() {
  favourites.webdb.open();
  favourites.webdb.createTable();
  //favourites.webdb.getAllTiles(loadTiles);
};

我在尝试向数据库添加数据时遇到错误: http://i.imgur.com/AGoBP9X.png

有人可以解释我的代码出了什么问题吗?

1 个答案:

答案 0 :(得分:0)

我的第一个猜测是favourites.webdb.db === null,因此没有方法transaction

出于这个原因,我会检查是否实际调用init。 (如果是这样,那么检查openDatabase的verison参数是否正确。在我发现的文档中,它应该是"1.0",而不仅仅是"1"