此代码必须向我添加到表中的内容发出警报。他没有提醒变量"hallo“的值。你知道这段代码出了什么问题吗?
<html>
<body>
<script>
var db = openDatabase('neueDb', '1.0', "Test DB", 2 * 1024 * 1024);
var hallo = "hallo1234";
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (log)');
tx.executeSql('INSERT INTO LOGS (log) VALUES ("foobar")');
tx.executeSql('INSERT INTO LOGS (log) VALUES ("logmsg")');
tx.executeSql('INSERT INTO LOGS (log) VALUES (?)', hallo);
});
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
alert(results.rows.item(i).log);
}
}, null);
});
</script>
</body>
谢谢你所有的回答!在爱中,德克斯特
发布于 2016-12-02 20:54:09
您忽略了db.transaction是异步的这一概念。
您期望它首先插入您的所有行,然后选择它们。实际上并不是这样的。
这大概就是你所需要的:
b.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (log)');
tx.executeSql('INSERT INTO LOGS (log) VALUES ("foobar")');
tx.executeSql('INSERT INTO LOGS (log) VALUES ("logmsg")');
tx.executeSql('INSERT INTO LOGS (log) VALUES (?)', [hallo]);
tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
alert(results.rows.item(i).log);
}
}, null);
});当然,理想情况下,tx.executeSql('SELECT * FROM LOGS'应该包装在另一个函数中。
还要注意@Jorge对你使用的语法的评论。
发布于 2016-12-02 20:58:10
对我来说,在Chrome中,我在执行tx.executeSql('INSERT INTO LOGS (log) VALUES (?)', hallo);时出现错误
VM109:1 Uncaught TypeError: Failed to execute 'executeSql' on 'SQLTransaction': The 2nd argument is neither an array, nor does it have indexed properties.(…)
我不知道为什么,我以前从来没有遇到过这个错误。但是如果我执行db.transaction(function (tx) { tx.executeSql('INSERT INTO LOGS (log) VALUES (?)', [hallo]); }),它就能正常工作,然后警报就会显示hallo value OK。
我认为您在插入值时出错,这就是它没有收到警报的原因。
https://stackoverflow.com/questions/40932611
复制相似问题