在处理完整个For循环后发出嵌套的HTML5 Web SQL查询

Nested HTML5 Web SQL Query Issued after Entire For Loop Processed

本文关键字:嵌套 HTML5 Web 查询 SQL 处理 循环 For      更新时间:2023-09-26

在下面列出的这个查询中,我的for循环正在执行4个值。在第一个警报(id)中,它向这4个不同的值发出警报。但是,在嵌套查询中,alert语句只打印出最后一个id值,4x具有不同的max(b.id)值。我很困惑。有人知道可能发生什么吗?比赛情况可能会发生吗?

我的目标是在嵌套查询中放置一个Ajax调用,该查询具有基于id和b.id的输入值。我目前正在这样做,但Ajax调用中"id"的值对于所有4个不同的调用都是相同的,这会混淆返回数据。谢谢

database.db.transaction(function (tx) {
            tx.executeSql('SELECT id, name from programs d', [], function (tx, results) {
                for (var i = 0; i < results.rows.length; i++) {
                    var id = results.rows.item(i)['id'];
                    var name = results.rows.item(i)['name'];
                        alert(id);
                    tx.executeSql('SELECT max(b.id) + 1 max from people b where b.sid = ?',
                        [id],
                        function (tx, results) {
                            lastRecord = results.rows.item(0)['max'];
                            alert(id + "last rec: " + name);
                        }
                    );
                }
            },
            function (event) { alert(event.message); });

根据我的评论,您需要返回一个闭合函数来正确绑定参数。

一个简单得多的例子如下:

运行此操作会产生4个警报,全部显示4:

for (i=0;i<4;i++) {
    setTimeout( function() { alert(i)}, 1000);
}

运行此操作会产生4个警报,分别显示0/4、1/4、2/4和3/4。

for (i=0;i<4;i++) {
    setTimeout(function(inneri) { 
        return( 
            function() { 
                alert(inneri + "/" + i);
            }
        );
    }(i), 1000);
}

其中,我将inneri命名为闭包时保留的值。请注意,i本身仍然是指外部作用域,因此是4(这在执行时是正确的,因为这是i从for循环中转储时的值,因为我们使用setTimeout()延迟执行

第一种情况是你正在做的事情的一个简单版本,而你想要第二种情况。

重写你的js(并希望我能得到所有这些(并且{在正确的地方:))给出:

database.db.transaction(function (tx) {
      tx.executeSql('SELECT id, name from programs d', [], function (tx, results) {
            for (var i = 0; i < results.rows.length; i++) {
                var id = results.rows.item(i)['id'];
                var name = results.rows.item(i)['name'];
                alert(id);
                tx.executeSql('SELECT max(b.id) + 1 max from people b where b.sid = ?',
                    [id],
                    function(innerId) { 
                       return (
                          function (tx, results) {
                                lastRecord = results.rows.item(0)['max'];
                                alert(innerId + "last rec: " + name);
                          }
                       );
                    }(id) //be careful to avoid the ";" here!
                );
            }
        },
        function (event) { alert(event.message); 
    });

我插入的位置:

 function(innerId) { 
    return (
         function (tx, results) {
             lastRecord = results.rows.item(0)['max'];
             alert(innerId + "last rec: " + name);
         }
    );
 }(id)

中。此函数通过(id)立即调用,并返回一个以txresults为参数并执行适当操作的函数。

我检查了大括号/括号,但没有直接的方法来验证我没有拼写错误。