Javascript Global Variable Problem
Solution 1:
I would assume that you're making an asynchronous AJAX call, so your alert()
fires before the response is received.
EDIT:As @Nick noted, this is not AJAX, but is an issue with it being asynchronous.
I don't know anything about the API you're using, but it would seem as though your alerts should be inside the dataHandler
method:
dataHandler: function (transaction, results) {
// Handle the resultsdata = results.rows;
alert(Log.object_toString(data) );
alert(Log.object_toString(data) );
returntrue;
},
Or should be in some other function that is called from inside dataHandler
.
dataHandler: function (transaction, results) {
// Handle the resultsdata = results.rows;
someFunction( data );
returntrue;
},
// ...
function someFunction( data ) {
alert(Log.object_toString(data) );
alert(Log.object_toString(data) );
}
The reason an alert()
in between makes it work, is that the pause gives the response a chance to return before the other alerts run.
Solution 2:
The problem is that if you access data right after you called exec the dataHandler callback wasn't called yet. The only way to make sure that you actually received your data from the query is to handle it within the callback itself. For that you could redesign your class a bit to allow the exec function to actually also take a callback function that will be called as soon as the query was executed successfully, eg
exec: function (query, params, onSuccess /*, onFailure*/) {
try {
var onFailure = arguments[3] || function(){};
this.mydb.transaction(function(transaction) {
transaction.executeSql(query, params, onSuccess, onFailure);
});
} catch(e) {
onFailure(e);
}
}
Then you can call your db.exec like this:
db.exec('SELECT * FROM erros;', null, function(rows) {
alert(Log.object_toString(rows));
}, function() {
var error = arguments[0] || {message: 'Unknown Exception'};
alert('An error occured: ' + error.message);
});
Post a Comment for "Javascript Global Variable Problem"