0

在我的示例中,我试图将变量(var ttoken)从一个函数传递到另一个函数并将其保存到 SQLite。编码环境是Phonegap(适用于android)。这是程序:

var ttoken;    // global var declaration
function handleLogin() {
var form = $("#loginForm");
var u = $("#username", form).val();
var p = $("#password", form).val();
if(u!= '' && p!= '') {
    $.post("http://localhost/login.php", {username:u, password:p}, function(data){
        if(data!='') {
            $.mobile.changePage("change_page.html");
            ttoken = data.token;
        } else {
            navigator.notification.alert("Error try again", function() {});
        }
    }, "json");
} else {
    navigator.notification.alert("Error, fields are emty", function() {});
}
return {tkn:ttoken};    // putting into array
openDB();
populateDB();
}

var db;
function openDB(){  // create database
    // 'Kurskoffer_DB' vol. 300 Kb
    db = window.openDatabase("Sample_DB", "1.0", "Samole DB", 300000);
    db.transaction(populateDB, errorCB, successCB);
}

function populateDB(tx){    // create 'settings' table
    var tooken = handleLogin();    // accessing the variable ttoken
    tx.executeSql('CREATE TABLE IF NOT EXISTS settings (id INTEGER PRIMARY KEY, token TEXT NOT NULL, sound TEXT NOT NULL, vibra TEXT NOT NULL)');
    tx.executeSql('INSERT INTO settings(id, token, sound, vibra) VALUES (1, "'+tooken.tkn+'", "on", "on")');
}

似乎根据变量传递规则的一切都可以,但是字段标记表中的插入结果是undefined。有谁知道为什么会这样?谢谢。

4

1 回答 1

0

$.post函数是异步的,这意味着handleLogin将在post回调触发之前返回,并且ttoken在返回的对象中保持未定义。

设置handleLogin为接受回调,该回调将在post已返回并ttoken已填充时触发。

就像是:

function handleLogin(callback) {
    var form = $("#loginForm");
    var u = $("#username", form).val();
    var p = $("#password", form).val();
    if(u!= '' && p!= '') {
        $.post("http://localhost/login.php", {username:u, password:p}, function(data){
            if(data!='') {
                $.mobile.changePage("change_page.html");
                ttoken = data.token;
                if (callback) callback();
            } else {
                navigator.notification.alert("Error try again", function() {});
            }
        }, "json");
    } else {
        navigator.notification.alert("Error, fields are emty", function() {});
    }
}

function populateDB(tx){    // create 'settings' table
    handleLogin(function() {
        tx.executeSql('CREATE TABLE IF NOT EXISTS settings (id INTEGER PRIMARY KEY, token TEXT NOT NULL, sound TEXT NOT NULL, vibra TEXT NOT NULL)');
        tx.executeSql('INSERT INTO settings(id, token, sound, vibra) VALUES (1, "'+ttoken+'", "on", "on")');
    });
}

由于ttoken是全局定义的,因此您不必担心将其作为参数传递。

于 2013-01-27T15:14:36.653 回答