亲爱的Stackoverflow用户,
我们创建的数据库如下:
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS Gerechten');
tx.executeSql('CREATE TABLE IF NOT EXISTS Gerechten (id INTEGER PRIMARY KEY AUTOINCREMENT, Cat TEXT NOT NULL, Name TEXT NOT NULL, Desc TEXT NOT NULL)');
tx.executeSql('INSERT INTO Gerechten(Cat,Name,Desc) VALUES ("Voorgerecht", "Tomatensoep", "Heerlijke romige tomatensoep")');
tx.executeSql('INSERT INTO Gerechten(Cat,Name,Desc) VALUES ("Hoofdgerecht", "Pizza", "Kaas en tomaat")');
tx.executeSql('INSERT INTO Gerechten(Cat,Name,Desc) VALUES ("Voorgerecht", "Groentensoep", "Goed gevulde groentensoep")');
tx.executeSql('INSERT INTO Gerechten(Cat,Name,Desc) VALUES ("Voorgerecht", "Kippensoep", "Kippensoep met stukjes kip")');
tx.executeSql('INSERT INTO Gerechten(Cat,Name,Desc) VALUES ("Hoofdgerecht", "Biefstuk", "Biefstuk, wordt geserveerd met patat of rijst")');
}
我的Javascript循环有问题,代码如下:
function queryDB(tx){
tx.executeSql('SELECT DISTINCT "Cat" FROM Gerechten',[],function (tx, results) {
var len = results.rows.length, i;
msg = "<p>Found rows: " + len + "</p>";
document.write(msg + '<br/>');
for (i = 0; i < len; i++){
document.write(results.rows.item(i).Cat + '<br/>');
tx.executeSql('SELECT * FROM Gerechten WHERE "Cat" ="'+results.rows.item(i).Cat+'"',[],function (tx, results2) {
var len2 = results2.rows.length, y;
msg = "<p>Found rows: " + len2 + "</p>";
document.write(msg + '<br/>');
for (y = 0; y < len2; y++){
document.write(results2.rows.item(y).Name + '<br/>');
}
}, null);
}
}, null);
}
代码的问题是首先输出类别,然后显示名称(按照正确的顺序):
Voorgerecht
Hoofdgerecht
Tomatensoep
Groentensoep
Kippensoep
Pizza
Biefstuk
正确的顺序应该是:
Voorgerecht
Tomatensoep
Groentensoep
Kippensoep
Hoofdgerecht
Pizza
Biefstuk
有谁知道如何解决这个问题?
亲切的问候,
丹尼斯
答案 0 :(得分:1)
你的问题是executeSql
异步执行你的函数(它的最后一个参数),所以你的外循环很可能在内循环的查询完成执行之前打印所有类别。
您应该只使用一个查询,以便您可以按正确的顺序处理所有结果。 尝试这样的事情:
SELECT * FROM Gerechten ORDER BY Cat
并在Cat
列中的值发生变化时打印该类别(请参阅Jose的回答)。
答案 1 :(得分:0)
老实说,你不需要多次查询数据库,假设:
SELECT * FROM Gerechten
,您的搜索结果包含以下内容you could do as below and still produce the same results。显然你需要实现它以匹配你的web sql数据库api,但逻辑应该保持不变。
var results = [
{
"Cat" : "Voorgerecht",
"Name" : "Tomatensoep",
"Desc" : "Heerlijke romige tomatensoep"
},{
"Cat" : "Hoofdgerecht",
"Name" : "Pizza",
"Desc" : "Kaas en tomaat"
},{
"Cat" : "Voorgerecht",
"Name" : "Groentensoep",
"Desc" : "Goed gevulde groentensoep"
},{
"Cat" : "Voorgerecht",
"Name" : "Kippensoep",
"Desc" : "Kippensoep met stukjes kip"
},{
"Cat" : "Hoofdgerecht",
"Name" : "Biefstuk",
"Desc" : "wordt geserveerd met patat of rijst"
}
];
//sorts by the Category
results.sort(compare);
var initial = "";
for(var y = 0; results.length; y++) {
if(initial != results[y].Cat){
initial = results[y].Cat;
document.write(initial + "<br/>");
}
document.write(" " + results[y].Name + "<br/>");
}
function compare(a,b) {
if (a.Cat < b.Cat)
return 1;
if (a.Cat > b.Cat)
return -1;
else
return 0;
}
输出
Voorgerecht
Tomatensoep
Groentensoep
Kippensoep
Hoofdgerecht
Pizza
Biefstuk