2014-01-19 126 views
0

我以某种方式设法插入文本字段的内容使用文本字段id与下面的代码,但宁愿将文本字段中的任何内容分配给变量,然后插入该变量的值。如何在SQLite中将变量值插入到我的数据库中?

var newName = document.getElementById("txNewName").value; 
var ing1 = document.getElementById("txIngredient1").value; 
var ing2 = document.getElementById("txIngredient2").value; 
var ing3 = document.getElementById("txIngredient3").value; 

db.transaction(function(transaction) { 
    transaction.executeSql('INSERT INTO MyRecipes(MyRecipeName, MyIngredient1, MyIngredient2, MyIngredient3) VALUES (?,?,?,?)',[$('#txNewName').val(), $('#txIngredient1').val(), $('#txIngredient2').val(), $('#txIngredient3').val()]); 
}); 

我正在使用SQLite,如果这有所作为,我是非常新的,所以将不胜感激任何帮助。

+0

作为另一一边,你是混合的JavaScript和jQuery - 更好地坚持jQuery的语法,如果你正在使用它。 – Turophile

回答

0

在给出的代码中,你的变量是在不同的作用域中声明的 - 所以在函数中这些值是不可知的。您可能需要使用全局变量,或将它们作为参数传递。下面我改变了将它们放入函数中的答案。这可能不是你想要的,但它会确认问题出在哪里:

db.transaction(function(transaction) { 
    var newName = document.getElementById("txNewName").value; 
    var ing1 = document.getElementById("txIngredient1").value; 
    var ing2 = document.getElementById("txIngredient2").value; 
    var ing3 = document.getElementById("txIngredient3").value; 
console.log('Inserting into the database ' + newName + ',' + ing1 +',' + ing2 + ',' + ing3); 
    transaction.executeSql('INSERT INTO MyRecipes(MyRecipeName, MyIngredient1, MyIngredient2, MyIngredient3) VALUES (?,?,?,?)',[newName, ing1, ing2, ing3]); 
}); 
+0

是的,数据库只显示'undefined undefined undefined undefined',就像我尝试过的大多数方法一样。 (还是)感谢你的建议。 – Marblex

+0

是的,在给出的代码中,你的变量被声明在一个不同的范围内 - 所以在函数中值不会被知道。您可能需要使用全局变量,或将它们作为参数传递。我改变了答案,将它们放入函数中。这可能不是你想要的,但它会确认问题出在哪里。 – Turophile

+0

当然,谢谢,但我已经尝试使变量为全局变量,并将它们作为参数传递,但数据库仍显示'undefined undefined undefined undefined'。 – Marblex

相关问题