Phonegap:登录成功时插入查询sqlite

时间:2015-06-27 00:05:02

标签: javascript android jquery sqlite cordova

我使用phonegap和jquery mobile构建移动应用程序hibrid基础。我的应用程序有一个登录系统,从服务器中的数据库检索数据,并在登录成功时将其插入sqlite,因此即使应用程序离线,应用程序也可以访问数据。 我使用来自litehelpers的插件。这是我在database.js中的sql connect脚本:

document.addEventListener("deviceready", connectDB, false);

var kode = JSON.parse(window.localStorage['konfirmasi']);

//create or open Database
function connectDB(){
  db = window.sqlitePlugin.openDatabase("konfirmasi", "1.0", "Data Konfirmasi Pengiriman", "1000");
  db.transaction(populateDB,successCB,errorCB);
}

//create table and insert some record
function populateDB(tx) {
    tx.executeSql("CREATE TABLE IF NOT EXISTS data_konfirmasi (kode_transaksi text, status text) UNIQUE(kode_transaksi)");
}

//function will be called when an error occurred
function errorCB(err) {
    console.log("Error processing SQL: "+err.code);
}

//function will be called when process succeed
function successCB() {
    console.log("Connected to database!");
    //db.transaction(queryDB,errorCB);
}

function insertDB(tx){
    for (var i = kode.length - 1; i >= 0; i--) {
        tx.executeSql("INSERT INTO data_konfirmasi VALUES ("+kode[i]+", 'Belum Terkirim');");
    };
}

function queryDB(){
    db.transaction(insertDB,errorCB,querySuccess);
}

function querySuccess(){
    console.log('Insert query success!');
}

function dropDB(){
    db.transaction(dropQuery,errorDrop,successDrop);
}

function dropQuery(tx){
    tx.executeSql("DROP TABLE IF EXIST data_konfirmasi");
}

function successDrop(){
    console.log('Drop table successful');
}

function errorDrop(err){
    console.log('Drop table unsuccessful, Error code: '+err.code);
}

function selectData(err){
    db.transaction(selectQuery, errorCB, successQuery)
}

function selectQuery(tx){
    tx.executeSql('SELECT * FROM data_konfirmasi',[], querySuccess, errorCB);
}

function querySuccess(tx, results) {
    console.log("Returned rows = " + results.rows.length);
    // this will be true since it was a select statement and so rowsAffected was 0
    if (!results.rowsAffected) {
        console.log('No rows affected!');
        return false;
    }
    // for an insert statement, this property will return the ID of the last inserted row
    console.log("Last inserted row ID = " + results.insertId);
}

然后,当用户第一次登录并成功时,它将使用json从服务器检索数据,我希望我的应用程序将检索到的数据插入到sqlite。那么,如何将查询仅用于登录成功?之后我想把它作为DROP表并在它注销时清除localStorage。 这是我的登录和注销脚本(main.js):

$(document).on('pageinit','#login',function(){
    $(document).on('click','#submit',function(){
        if($('#username').val().length>0&&$('#password').val().length>0){
            var un = $('#username').val();
            var pw = $('#password').val();
            $.ajax({
                url:'http://qrkonfirmasi.16mb.com/delivery/login.php',
                data:{  username : un,
                        password : pw
                    },
                type:'post',
                async:'false',
                dataType: 'json',
                beforeSend:function(){
                    $.mobile.loading('show',{theme:"a",text:"Please wait...",textonly:true,textVisible:true});
                },
                complete:function(){
                    $.mobile.loading('hide');
                },
                success:function(result){
                    console.log(result);
                    if(result.status==true){
                        user.name=result.message;
                        window.localStorage.setItem('konfirmasi', JSON.stringify(result.data));
                        console.log('Kode: ', JSON.parse(window.localStorage['konfirmasi']));
                    var kode = JSON.parse(window.localStorage['konfirmasi']);
                    console.log('Array length: '+kode.length);
                        queryDB();
                        console.log('Login berhasil');
                        $.mobile.changePage("#konfirmasi");
                        window.localStorage.setItem('uname', un);
                        window.localStorage.setItem('passwd', pw);                        
                        console.log(window.localStorage['uname']);
                    }else{
                        alert('Login gagal. Username atau password tidak sesuai');
                    }
                },
                error:function(request,error){
                    alert('Koneksi error. Silahkan coba beberapa saat lagi!');
                }
            });
        }else{
            alert('Masukkan username dan password!');
        }
        return false;
    });
});

$(document).on('pagebeforeshow','#konfirmasi',function(){
    $.mobile.activePage.find('.welcome').html('<h3>Selamat Datang '+user.name+'</h3>' );
});

$(document).off('click').on('click','#logout',function(){
    window.localStorage.clear();
    dropDB();
    $.mobile.changePage("#home");
});

function exitFromApp(){
    navigator.app.exitApp();
}

那么,我是否以正确的方式登出注销脚本?我不知道它是否有效,因为我仍然无法尝试,因为当我尝试使用插入查询时,登录脚本仍然出错。

有人可以帮我完成吗?

1 个答案:

答案 0 :(得分:1)

你在哪里调用这段代码?

function insertDB(tx,val){
            for (var i = kode.length - 1; i >= 0; i--) {
                tx.executeSql('INSERT INTO konfirmasi VALUES ('+a[i]+');',querySuccess,errorCB);
            };
        }

如果从事务中调用它,则“val”参数不会直接传递给insertDB函数。您可以尝试以下方法:

val = [];
db.transaction(function(tx){
insertDB(tx, val);
}, errorCB);

此外,请确保stements始终在db.transaction上下文中运行

玩得开心!