简体   繁体   English

访问WebSQL函数中的变量

[英]Accessing variable inside WebSQL Function

I am using the following code 我使用以下代码

var Year12=new Array();

GetYear(function(Year12) 
{
alert(Year12);
});

   function GetYear(callback) 
     {

       var selectAllStatement = "SELECT DISTINCT year FROM mytable";
       var db = openDatabase("Postit", "1.0", "Notebook", 200000);
       var dataset;
       alert("1");
       db.transaction(function(tx) {
       alert("2");

           tx.executeSql(selectAllStatement, [], function(tx, result) 
           {
           alert("3");
          dataset = result.rows;

          for (var i = 0, item = null; i < dataset.length; i++)
           {

                 item = dataset.item(i);
                 Year12[i]=item['year'];

           }
          callback(Year12);
       });
     });
    }

Here the tx.executeSql statements are not getting executed means alert 3 is not displaying.Is there any way to do this 这里没有执行tx.executeSql语句意味着警报3没有显示。有没有办法做到这一点

The db.transaction and tx.executeSql calls are asynchronous, hence the callback functions. db.transactiontx.executeSql调用是异步的,因此是回调函数。 That means that GetYear will finish executing and return before the tx.executeSql callback will populate your Year12 array. 这意味着GetYear将在tx.executeSql回调填充Year12数组之前完成执行并返回。

Once you have asynchronous behavior and callbacks, the only sensible solution is, of course, more callbacks. 一旦你有异步行为和回调,唯一明智的解决方案当然是更多的回调。 You need a structure more like this: 你需要一个更像这样的结构:

function GetYear(callback) {
    //...
    db.transaction(function(tx) {
        //...
        tx.executeSql(selectuniqueyearStatement, [], function(tx, result) {
            var Year12 = [ ];
            //... populate the locale Year12 using result.rows
            callback(Year12);
        });
    });
}

and then use it like this: 然后像这样使用它:

GetYear(function(year12) {
    // Do whatever you need to do with the year12 array...
});

Basically the same code structure and strategies that you use with AJAX calls. 基本上与AJAX调用使用的代码结构和策略相同。

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

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