Javascript html5 database transaction problem in loops
I'm hittig my head on this and i will be glad for any help. I need to store in a database a context (a list of string ids) for another page. I open a page with a list of artworks and this page save into the database those artowrks ids. When i click on an artwork i open its webpage but i can access the database to know the context and refer to the next and prev artwork.
This is my code to retrieve the contex:
updateContext = function () {
alert("updating context");
try {
mydb.transaction(
function(transaction) {
transaction.executeSql("select artworks.number from artworks, collections whe开发者_运维问答re collections.id = artworks.section_id and collections.short_name in ('cro', 'cra', 'crp', 'crm');", [], contextDataHandler, errorHandler);
});
} catch(e) {
alert(e.message);
}
}
the contextDatahandler function then iterates through the results and fill again the current_context table:
contextDataHandler = function(transaction, results) {
try {
mydb.transaction(
function(transaction) {
transaction.executeSql("drop table current_context;", [], nullDataHandler, errorHandler);
transaction.executeSql("create table current_context(id String);", [], nullDataHandler, errorHandler);
}
)
}
catch(e) {
alert(e.message);
}
var s = "";
for (var i=0; i < results.rows.length; i++) {
var item = results.rows.item(0);
s += item['number'] + " ";
mydb.transaction(
function(tx) {
tx.executeSql("insert into current_context(id) values (?);", [item['number']]);
}
)
}
alert(s);
}
the result is, i get the current_context table deleted, recreated, and filled, but all the rows are filled with the LAST artwork id. the query to retrieve the artworks ids works, so i think it's a transaction problem, but i cant figure out where.
thanks for any help
i still dont understand where my code is wrong, but i solved by using:
contextDataHandler = function(transaction, results) {
try {
mydb.transaction(
function(transaction) {
transaction.executeSql("drop table current_context;", [], nullDataHandler, errorHandler);
transaction.executeSql("create table current_context(id String);", [], nullDataHandler, errorHandler);
for(var i=0; i < results.rows.length; i++) {
var item = results.rows.item(i);
transaction.executeSql("insert into current_context(id) values (?);", [item['number']], nullDataHandler, errorHandler);
}
}
)
}
catch(e) {
alert(e.message);
}
}
(Assuming the fact that in the for loop you always get results.rows.item(0), instead of indexing all the items, is a typo when pasting the code in the question)
You might be hitting the "Infamous Loop Problem" with variable bindings (described by Robert Nyman and James Padolsey (original page disappeard, so link to Google cache)).
精彩评论