开发者

WebSQL in Synchronous mode... is it possible?

I've started using HTML5 and WebSQL, and I quickly ran into a problem: all the DB calls are asynchronous. I come from PHP programming, where all the calls are synchronous, and I'm at a loss with the asynch stuff.

Basically, I open the DB and run a query, which uses an id parameter I'm passing to the page via GET (i.e. http://myserver.com/mypage.html?id=123). I need the result in globalResult:

id=window.location.search.substring(1).split('=')[1];
db=openDatabase("testDB", "1.0", "Test Database", 10000000);

db.transaction(function(tx)
{
    tx.executeSql("SELECT * FROM testTable WHERE id="+id,[],successCB,errorCB);
});

function errorCB(tx,err)
{
    alert("Error processing SQL: "+err);
}

function successCB(tx,result)
{
    globalResult=result.rows.item(0)['description'];
}

...Javascript code which needs 开发者_如何学运维globalResult to be set...

Now, as the query is asynchronous, the interpreter starts executing the rest of the code before having the results, and of course it doesn't work.

Is there any trick to run queries synchronously, or some technique to play with the callback functions in order to solve this problem?

Thanks in advance, guys :)


I actually never ran into the same problem as you, my implementation sample of WebSQL:

var projectName = {};
projectName.webdb = {};
projectName.webdb.db = null;
projectName.webdb.open = function() {
    projectName.webdb.db = openDatabase('Database Name', '1.0', 'description', 10 * 1024 * 1024);
}
projectName.webdb.onError = function(tx, e) {alert('Database Error: ' + e.message );}
projectName.webdb.onSuccess = function(tx, r) {}
projectName.webdb.getPeopleForExample = function() {
    projectName.webdb.db.transaction(function(tx) {
        tx.executeSql('SELECT * FROM people WHERE id=23', [], loadPeople, projectName.webdb.onError);
    });
}

function loadPeople(tx, rs) {
    for (var i=0; i < rs.rows.length; i++) {
        var name = rs.rows.item(i).name;
        var email = rs.rows.item(i).email;
        // now you do whatever you want with the data..
    }
}

Then from anywhere in the procedural code I just call
projectName.webdb.getPeopleForExample();

I think you'll get the idea from the code sample :)


In the end, the easiest solution I found was to change the flow of the Javascript. Instead of waiting for the results to populate my page (PHP-like), I went for a blank structure which gets populated in the end by the "success" callback function.

Also, I recommend using jquery-sql, which greatly simplifies the code when it comes to WebSQL.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜