0

我在我的 phonegap 应用程序的返回 getJSON 响应函数中使用 sqlite 查询时遇到问题。

我尝试应用此代码,但我所拥有的只是错误

INVALID_STATE_ERR:DOM 异常 11:尝试使用不可用或不再可用的对象。

我的代码是

<script>
     document.addEventListener("deviceready", onDeviceReady, false);
     function onDeviceReady() {
        // open DB connection
         var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
         db.transaction(populateDB, errorCB, successCB);
    }

    function populateDB(tx) {

         tx.executeSql('DROP TABLE IF EXISTS buses');
         tx.executeSql('CREATE TABLE IF NOT EXISTS buses (bus_id INTEGER PRIMARY KEY,bus_no TEXT, bus_time TEXT,from_loc TEXT,to_loc TEXT,route TEXT)');
         $.getJSON('http://myegy.me/maryam/asem/api.php?table=trip', function(data) {
              $.each(data, function(key, val) {

                    tx.executeSql('INSERT INTO buses (bus_no,from_loc,to_loc,route) VALUES ("'+val['trip_number']+'","'+val['from_id']+'","'+val['to_id']+'","'+val['stop_station']+'")');
              });
            });

         tx.executeSql('DROP TABLE IF EXISTS bus_stations');
         tx.executeSql('CREATE TABLE IF NOT EXISTS bus_stations (id INTEGER PRIMARY KEY,station_name TEXT, station_description TEXT,station_lat TEXT,station_long TEXT)');
         $.getJSON('http://myegy.me/maryam/asem/api.php?table=station', function(data) {
              $.each(data, function(key, val) {

                    tx.executeSql('INSERT INTO bus_stations (station_name,station_lat,station_long) VALUES ("'+val['station_name']+'","'+val['latitude']+'","'+val['longitude']+'")');
              });
            });

    }

    </script>

这两行的问题

 tx.executeSql('INSERT INTO buses (bus_no,from_loc,to_loc,route) VALUES ("'+val['trip_number']+'","'+val['from_id']+'","'+val['to_id']+'","'+val['stop_station']+'")');

tx.executeSql('INSERT INTO bus_stations (station_name,station_lat,station_long) VALUES ("'+val['station_name']+'","'+val['latitude']+'","'+val['longitude']+'")');
4

1 回答 1

0

您必须将 $.getJSON 语句移动到 successCB 函数,我还建议将 json 数据作为参数传递给将数据作为 db.transaction 处理的函数。

function successCB() {
    $.getJSON('http://myegy.me/maryam/asem/api.php?table=trip', function (data) {
        setBuses(data);
    }
}

function setBuses(data) {
    this.db.transaction(
        function (tx) {
            var l = data.length;
            var sql = 'INSERT INTO buses (bus_no,from_loc,to_loc,route) VALUES (?,?,?,?)';
            var b;
            for (var i = 0; i < l; i++) {
                b = data[i];
                var params = [b.trip_number,b.from_id,b.to_id,b.stop_station];
                tx.executeSql(sql, params);
            }
        },
        errorCB,
        function () {}
    );
}

我建议您阅读 Appliness ( http://www.appliness.com/download/ ) 2012 年 6 月的文章,由 Christophe Coenraets 撰写,名为“离线数据同步”。

于 2013-08-28T19:06:57.093 回答