简体   繁体   English

从WebSQL Javascript命令返回变量

[英]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. 我正在尝试使用Javascript查询WebSQL数据库,以返回单个最高数据行的'id'列的值。

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. 我相信查询正在执行,因为我收到成功的SELECTING警报。 The alert(xyz) is simply returning value nil. alert(xyz)仅返回值nil。

How can I get the data from the SQL database into a Javascript variable? 如何将数据从SQL数据库获取到Javascript变量中?

Thanks! 谢谢!

EDIT: The following suggested code change results in a ReferenceError: Can't find variable: results 编辑:以下建议的代码更改导致ReferenceError:找不到变量:结果

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 您在executeSql参数列表中缺少逗号

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 . 结果对象包含rows属性,而不是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. transaction()需要3个回调,第一个是在打开事务时将执行的回调。 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. 您正在使用错误回调,但将其视为成功回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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