开发者

HTML5 database table - check if empty

I'm attempting to write a function to determine if an html5 websql db table is empty. Code is below. I put alerts in there to see what is happening. When this function runs the alert at bottom pops up first. Although the table is empty the return value is false.

function tableisempty() {
tf = false;
query = "SELECT * FROM OLL;";

localDB.transaction(function(transaction){
         transaction.executeSql(query, [], function(开发者_如何学JAVAtx, results){

             if (results.rows.length == 0) { 
                  tf = true;
                  alert ("table has "+results.rows.length+" rows. returning "+tf);
                 }   else    {
                  tf = false;    
                  alert ("table is not empty. returning "+tf); 
                 }                               
         }, errorHandler);              
});

alert ("return value is " + tf);

return tf;

}


Based on your comment and the w3 page, the query is happening async. The solution to your problem really depends on your js code structure.

Option 1:

Move tf outside the function (and add a var in front) and completely remove the return and alert right before it. When your callback gets called it will change the value of tf and the rest of your code can reference it is normal.

Option 2:

according to this SO question, you may be able to just change your call (elsewhere in your code I presume) from openDatabase to openDatabaseSync to enable synchronous operations.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜