在我的示例中,我尝试将变量(varttoken)从一个函数传递到另一个函数并将其保存到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")');
}
似乎根据变量传递规则的所有内容都可以,但是字段标记表中的插入结果未定义。有谁知道为什么会这样?谢谢。
$.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
是全局定义的,因此您不必担心将其作为参数传递。