在我的示例中,我试图将变量( 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")');
}
根据变量传递规则似乎一切正常,但字段标记表中的插入结果是未定义。有谁知道为什么会这样?感谢。
答案 0 :(得分: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
是全局定义的,因此您不必担心将其作为参数传递。