我现在正在学习如何使用phonegap并且学习进展顺利但我在phoneGap Api中遇到了全局变量。实际上我首先从xml文件中获取结果,然后将数据插入到数据库中。我已经完成了这项工作,但现在我想得到插入行的最后一个id,然后插入另一个表,因为在xml中有子节点。
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS fruit');
tx.executeSql('DROP TABLE IF EXISTS fruit_benefit');
tx.executeSql('CREATE TABLE IF NOT EXISTS fruit (id INTEGER NOT NULL PRIMARY KEY, fname,fsname,fruit_icon,fruit_image)');
tx.executeSql('CREATE TABLE IF NOT EXISTS fruit_benefit (id INTEGER NOT NULL PRIMARY KEY, benefit, fruit_id)');
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('fruit').each(function(){
var fname = $(this).find('fname').text();
var fsname = $(this).find('fsname').text();
var fruit_icon = $(this).find('fruit_icon').text();
var fruit_image = $(this).find('fruit_image').text();
//$('<div class="items" id="link_'+fname+'"></div>').html('<a href="'+fsname+'">'+fname+'</a>').appendTo('#lbUsers');
db.transaction(function(transaction) {
transaction.executeSql('INSERT INTO fruit (fname,fsname,fruit_icon,fruit_image) VALUES (?,?,?,?)',[fname, fsname, fruit_icon, fruit_image],function(transaction, results){
var lastId = results.insertId;
},nullHandler,errorHandler);
});
alert(lastId);
});
}
});
}
var lastId = results.insertId; //The last inserted id is shown here.
alert(lastId); //I want to show last inserted id here
我做了什么。
javascript全局变量,localstorage但两者都无效..
答案 0 :(得分:0)
你甚至不需要它是全球性的。在函数中但在foreach之前定义lastId。如果这不起作用,那么通过移动var lastId,使其成为全局应该真的有效;函数populateDB()
之前的行function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS fruit');
tx.executeSql('DROP TABLE IF EXISTS fruit_benefit');
tx.executeSql('CREATE TABLE IF NOT EXISTS fruit (id INTEGER NOT NULL PRIMARY KEY, fname,fsname,fruit_icon,fruit_image)');
tx.executeSql('CREATE TABLE IF NOT EXISTS fruit_benefit (id INTEGER NOT NULL PRIMARY KEY, benefit, fruit_id)');
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: function(xml) {
var lastId;
$(xml).find('fruit').each(function(){
var fname = $(this).find('fname').text();
var fsname = $(this).find('fsname').text();
var fruit_icon = $(this).find('fruit_icon').text();
var fruit_image = $(this).find('fruit_image').text();
//$('<div class="items" id="link_'+fname+'"></div>').html('<a href="'+fsname+'">'+fname+'</a>').appendTo('#lbUsers');
db.transaction(function(transaction) {
transaction.executeSql('INSERT INTO fruit (fname,fsname,fruit_icon,fruit_image) VALUES (?,?,?,?)',[fname, fsname, fruit_icon, fruit_image],function(transaction, results){
lastId = results.insertId;
},nullHandler,errorHandler);
});
alert(lastId);
});
}
});
}