这段代码有什么问题

时间:2014-03-26 18:20:37

标签: jquery sqlite cordova

我正在关注this example

我一遍又一遍地查看代码,它似乎与示例几乎相同,但getOrdersSuccess永远不会被调用。日志显示" setupTable"和" getOrders"两个都被叫了。 getOrdersSuccess中没有任何内容被记录下来。

function onDeviceReady() {
    if( window.isphone ) {
    var db = window.openDatabase("Database", "1.0", "The Database", 200000);
    db.transaction(setupTable, errorCB, getOrders);
    }
}
function setupTable(tx){
    $('#log').append("<p>setupTable</p>");
        tx.executeSql('create table if not exists orders (Id INTEGER PRIMARY KEY, name, isSubmitted, date)');
}
function getOrders() {
        $('#log').append("<p>getOrders</p>");
        db.transaction(function(tx){
            tx.executeSql('SELECT Id, name FROM orders', [], getOrdersSuccess, errorCB);
        }, errorCB);
    }
    // Query the success callback
    //
function getOrdersSuccess(tx, results) {
    $('#log').append("<p>getOrdersSuccess</p>");
        var len = results.rows.length;
        $('#log').append("<p>Orders table: " + len + " rows found.</p>");
        $('#current').html('');
        for (var i=0; i<len; i++){
            $('#log').append("<p>Row = " + i + " ID = " + results.rows.item(i).Id + " Name =  " + results.rows.item(i).name + "</p>");
            $('#current').append('<p>'+results.rows.item(i).Id+'---'+results.rows.item(i).name+'</p>');
        }
    }
function errorCB(err) {
        $('#log').append("<p>Error processing SQL: "+err.code+"</p>");
    }

1 个答案:

答案 0 :(得分:1)

在任何函数之外定义var db;,然后像这样修改onDeviceReady

var db;
function onDeviceReady() {
    if( window.isphone ) {
        db = window.openDatabase("Database", "1.0", "The Database", 200000);
        db.transaction(setupTable, errorCB, getOrders);
    }
}

问题是,如果您在var db内定义onDeviceReady,则其范围限定为该函数,且无法在函数getOrders中访问