调用Javascript函数来获取sql查询的结果集,并将它们打印在html表中

Call Javascript function to get resultset of sql query and print them in html table

本文关键字:打印 表中 html 函数 Javascript 获取 sql 结果 查询 调用      更新时间:2023-09-26

我正在使用Phonegap和jquery-Mobile-1.4.5创建一个跨平台的应用程序。因为我是一个Java开发人员,Java脚本对我来说是一个非常新的概念。我正在创建一个简单的应用程序,其中我有一个 html 表,我想在其中显示来自数据库表的选择查询。从这里我找到了如何向函数发送回调。但我的问题是,

  1. onload没有调用我的 showContact(resultSet ( 函数

  2. 如何在<tbody>标签中打印resultSet,我不想在showContact(resultSet)函数中使用javascript连接。>

我的索引.html文件的一部分

<table data-role="table" id="table-custom-2"  onload="showContact(resultSet)" >
            <thead>
                <tr class="ui-bar-d">
                    <th>Id</th>
                    <th>Name</th>
                    <th>Number</th>
                </tr>
            </thead>
            <tbody>
                <!--Print the resultSet data with a for loop here-->
            </tbody>
        </table>

我的脚本代码

function showContact(resultSet){
             var db= window.openDatabase("appDb","1.0","appDb",200000);
                selectRow("SELECT * FROM contact;", function(resultSet) {
                    console.log(resultSet);
                //Don't want to access the <table> from here
                  });
        }
        /** Select Row from Table **/ 
        function selectRow(query, callBack){ 
           var result = [];
           db.transaction(function (tx) {
              tx.executeSql(query, [], function(tx, rs){
                 for(var i=0; i<rs.rows.length; i++) {
                    var row = rs.rows.item(i)
                    result[i] = { id: row['id'],
                                  name: row['name'],
                                  number: row['number']
                    }
                 }
                 callBack(result); 
              }, errorHandler);
           });
        } 

您可以将从数据库获取的数据框在表行中,并将其分配给表正文。请参阅以下代码,

您可以在页面加载时selectrow()调用该函数

<table data-role="table" id="table-custom-2">
<thead>
    <tr class="ui-bar-d">
        <th>Id</th>
        <th>Name</th>
        <th>Number</th>
    </tr>
</thead>
<tbody id="contactlist">
<!--Print the resultSet data with a for loop here-->
</tbody>
</table>
<script>
$(document).ready(function($) {
    var db= window.openDatabase("appDb","1.0","appDb",200000);
    selectrow();
}); 
function selectrow(){
    db.transaction(function (tx) {
        tx.executeSql("SELECT * FROM contact", [], function(tx, rs){
            var output = '';
            for(var i=0; i<rs.rows.length; i++) {
                var row = rs.rows.item(i)
                output += '<tr><td>' + row['id'] + '</td><td>' + row['name'] + '</td><td>' + row['number'] + '</td></tr>';
            }
            $('#contactlist').html(output);
        }, errorHandler);
    });
}
</script>