无法使用getElementById将表单数据传递给SQLite

时间:2013-09-10 11:23:41

标签: javascript sqlite

我无法使用getElementById将数据从HTML表单传递到SQLite。

这是一个非常简单的代码,用于了解如何使用SQLite进行永久存储。

我的代码:

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
var db = openDatabase('sightings', '1.0', 'Test DB', 2 * 1024 * 1024);
var msg;


function InsertValues() {
var mydata = document.getElementById("CommonName").value;
db.transaction(function (tx) {      
  tx.executeSql('CREATE TABLE IF NOT EXISTS Sights (CommonName CHAR(17), location CHAR(32), datte CHAR(10), Observations CHAR(90))');
  tx.executeSql('INSERT INTO Sights (CommonName,location,datte,Observations) VALUES (mydata,"loobo","loobo","loobo")');
  msg = '<p>Log message created and row inserted.</p>';
  document.querySelector('#status').innerHTML =  msg;
});
}


function myfunction2() {
db.transaction(function (tx) {
  tx.executeSql('SELECT * FROM Sights', [], function (tx, results) {
   var len = results.rows.length, i;
   msg = "<p>Found rows: " + len + "</p>";
   document.querySelector('#status').innerHTML +=  msg;
   for (i = 0; i < len; i++){
     msg = "<p><b>" + results.rows.item(i).CommonName + "</b></p>";
     document.querySelector('#status').innerHTML +=  msg;
   }
 }, null);
});
}
</script>

</head>


<body>
<div class="observation">
  <h1></h1>
  <form action="#" method="post">
    <fieldset>
      <label for="name" >Common Name:</label>
      <input type="text" id="CommonName" placeholder=" Bird common Name" />
      <label for="name" >Location:</label>
      <input type="text" id="location" placeholder=" Where you see it" />
      <label for="email">Date</label>
      <input type="date" id="date" placeholder="mm/dd/yyy" /> 
      <label for="message">Observations:</label>
      <textarea id=" Observations" placeholder="What you see"></textarea>    
    <input type="submit" value="Register" onclick="InsertValues();">        
    </fieldset>
  </form>

</div>

 <script type="text/javascript">
            myfunction2();
 </script>
<div id="status" name="status">Status Message</div>

</body>
</html>

阻止数据从HTML表单流向SQLite的问题是什么?

1 个答案:

答案 0 :(得分:0)

要将代码中的字符串值转换为SQL语句,请使用参数:

tx.executeSql('INSERT INTO Sights (CommonName,location,datte,Observations) '+
              'VALUES (?, ?, ?, ?)',
              [mydata, 'loobo', 'loobo', 'loobo']);