关于HTML5网站的Sqlite实现,我有几个问题。
首先,我正在尝试使用同步数据库调用openDatabaseSync方法,但它似乎不起作用......有人已经使用它并可以帮助我吗?
另外,我正在努力尝试通过数据库查询处理结果返回。我希望我的函数能够返回一本书,如下所示:
function searchByKeywordId(kw_id, element) {
cleanSearch();
element.innerHTML = "No result...";
var books = new Array();
db.transaction(function (tx) {
tx.executeSql("SELECT b.BK_TITLE,b.BK_URL, b.BK_THUMBNAIL_URL FROM KEYWORDS k INNER JOIN CATALOG_ITEMS c on k.KW_ID = c.KW_ID INNER JOIN BOOKS b on c.BK_ID = b.BK_ID WHERE k.KW_ID = ? GROUP BY b.BK_TITLE,b.BK_URL",[kw_id], function (tx, results) {
if (results.rows.length > 0) {
var html = "";
for (var i = 0; i < results.rows.length; i++) {
var bookId = results.rows.item(i).BK_ID;
var bookUrl = results.rows.item(i).BK_URL;
var bookTitle = results.rows.item(i).BK_TITLE;
var bookThumbnailUrl = results.rows.item(i).BK_THUMBNAIL_URL;
var book = new Book(bookId,bookTitle,bookUrl,bookThumbnailUrl);
books.push(book);
/*html += "<div class='x_container' id='calibre:book:" + bookId + "'>";
html += "<div class='cover'>";
html += "</div></div>";*/
html += "<a href='" + bookUrl + "' title=\"" + bookTitle + "\" target='_new'><img src='" + bookThumbnailUrl + "'></a> ";
}
//html += "</div>";
element.innerHTML = html;
}
});
});
return books; }
显然,在回调方法中添加书籍不起作用......你是否看到了我可以实现的方法?这样我就不必从我的数据库方法中写入文档......
谢谢!
答案 0 :(得分:0)
在stackoverflow上用javascript和“不能正常工作”的问题通常是一个缺失的paren :)但是我没有在你的代码中找到一个。
我看到了一些可疑的语法,[kw_id], << did we really mean an array here, or are we de-referencing something...
在任何情况下,如果这不是一个错误,我会从简化事情开始,而不是多功能化你的功能。
function searchByKeywordId(kw_id, element) {
cleanSearch();
var books = new Array();
db.transaction(function (tx) {
tx.executeSql("SELECT b.BK_TITLE,b.BK_URL, b.BK_THUMBNAIL_URL FROM KEYWORDS k INNER JOIN CATALOG_ITEMS c on k.KW_ID = c.KW_ID INNER JOIN BOOKS b on c.BK_ID = b.BK_ID WHERE k.KW_ID = ? GROUP BY b.BK_TITLE,b.BK_URL",[kw_id], function (tx, results) {
if (results.rows.length > 0) {
var html = "";
for (var i = 0; i < results.rows.length; i++) {
var bookId = results.rows.item(i).BK_ID;
var bookUrl = results.rows.item(i).BK_URL;
var bookTitle = results.rows.item(i).BK_TITLE;
var bookThumbnailUrl = results.rows.item(i).BK_THUMBNAIL_URL;
var book = new Book(bookId,bookTitle,bookUrl,bookThumbnailUrl);
books.push(book);
} // end for loop
} // end if block
} // end execute callback
); // end executeSql call
} // end transaction function argument
); // end db.transaction call
return books;
}
然后你调用这个函数的地方做了这样的事情:
var html="";
for (i=0; i<books.length; i++) {
html += "<a href='" + books[i].url + "' title=\"" + books[i].title + "\" target='_new'><img src='" + books[i].thumbnailUrl + "'></a> ";
}
if (html == "") {
html = "No result...";
}
element.innerHTML = html; // consider using jQuery here for browser compatability reasons
这将简化在firebug或其他任何地方的代码调试,并且更具可读性。以后如果您需要性能,可以尝试重新组合并使用现有循环作为优化...过早优化通常是一个坏主意。写出有效的清晰代码。即使你知道你应该优化它,让它工作,然后在它工作后优化它(最好在你证明你确实需要优化它之后)。