以下函数始终返回'Inserted serial:undefined'。我很难意识到它为什么这样做,如果在db.transaction之前我console.log
那么它输出一个序列(只是一个数字)。为什么db.transaction data [i]内部突然未定义?
var localSerials = [340, 234, 545, 239, 546];
function downloadUpdates(localSerials) {
console.log("Updating local database...");
$.getJSON("update.php", function(data) {
for (var i = 0; i < data.length; i++) {
if (localSerials.indexOf(data[i]) == -1) {
db.transaction(function (tx) {
tx.executeSql('INSERT INTO serials (serial) VALUES (' + data[i] + ')');
console.log("Inserted serial: " + data[i]);
});
}
}
});
}
答案 0 :(得分:1)
您的异步事务位于for循环中,这会导致创建许多并行事务而不重用它们。将事务放在循环之外,并为所有请求重用事务。
var localSerials = [340, 234, 545, 239, 546];
function downloadUpdates(localSerials) {
console.log("Updating local database...");
$.getJSON("update.php", function(data) {
db.transaction(function (tx) {
for (var i = 0; i < data.length; i++) {
if (localSerials.indexOf(data[i]) == -1) {
tx.executeSql('INSERT INTO serials (serial) VALUES (' + data[i] + ')');
console.log("Inserted serial: " + data[i]);
});
}
}
});
}