Pages

Subscribe:

2013年9月2日 星期一

Web SQL要注意非同步的問題

HTML5的Web SQL是很重要的,未來在開發行動網頁或手機APP一定會用到的。不過,使用Web SQL要注意非同步的問題:Html5 WebSql transaction behaves strangely with alert,這個問題與Javascrit程式可以非同步執行的情況差不多、解決方案也一樣就是善用(jQuery) Callback FunctionJavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors.To prevent this, you can create a callback function.A callback function is executed after the current effect is finished. 而Web SQL的Callbak寫法最簡單的例子就像這個:WebSQL and Javascript Order of Operation
db.transaction(
        function (transaction) {
        transaction.executeSql(
        'SELECT * FROM contacts WHERE id = ?;',
        [id],
        function (transaction, result) {
           alert("1");
           if (result.rows.length != 0) {
            user = result.rows.item(0).name;
           } else {}
        },
        errorHandler);
    });
alert("2");
message = id + '%1E' + name;
瞭解上述的Web SQL程式設計概念之後,更進一步就可以自己再練習做出通訊錄或便利貼的功能囉,可以參考下列的教學範例:

沒有留言:

張貼留言