简体   繁体   中英

Return a variable from a WebSQL Javascript command

I'm trying to query a WebSQL database using Javascript to return the value of the 'id' column for the single highest data line.

db.transaction(function(tx) {
   //
   // PROBLEM AREA
   // How to get the data into a variable?
   //

   var xyz = 0;

   tx.executeSql('SELECT MAX(id) FROM WORKOUTS ORDER BY id DESC' [],function(tx, results) {
     var xyz = results.row.id, i;
     alert('Alert 2');
     alert(xyz);
   });

}, function(){
    alert('success SELECTING!');
}); // End transaction

I believe the query is executing as I am getting the success SELECTING alert. The alert(xyz) is simply returning value nil.

How can I get the data from the SQL database into a Javascript variable?

Thanks!

EDIT: The following suggested code change results in a ReferenceError: Can't find variable: results

function myTransaction(cb)
{
    db.transaction(function(tx) {
        tx.executeSql('SELECT MAX(id) FROM WORKOUTS ORDER BY id DESC', [], function(tx, results) {
        cb(results); }); 
    },function(){
        alert('success SELECTING!');
    }); // End transaction
}

myTransaction(function(results) { alert(results); });

A few things to note:

You're missing a comma in your executeSql parameter list

tx.executeSql('SELECT MAX(id) FROM WORKOUTS ORDER BY id DESC', [],function(tx, results) {

NOT

tx.executeSql('SELECT MAX(id) FROM WORKOUTS ORDER BY id DESC' [],function(tx, results) {

The results object contains a rows attribute, not a row .

So you want to use

results.rows.item(0)

NOT

results.row

transaction() takes 3 callbacks, the first is the callback which will be executed when the transaction is opened. The second is the error callback and the third is the success callback. You're using the error callback but treating it like a success callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM