显示从Interface on Interface(JavaScript / HTML / SQLite)获取的结果

时间:2016-03-17 18:19:36

标签: javascript html sql database sqlite

我想从数据库中获取记录,我希望数据显示在屏幕上。

从下面的代码中你可以看到我的查询是,如果数据库包含LIKE(数据输入),那么用" Event Found"提醒用户,如果没有找到数据,那么"没有事件!"。

但是,现在我想实际在屏幕上的表格上显示结果,或者哪种方式可以显示。

我知道你可以在javascript函数中创建和显示表格,但我不太清楚如何解决这个问题。有人可以帮助我吗? :)

function fetchEvent()
         {
      db = window.openDatabase("SoccerEarth", "2.0", "SoccerEarthDB", 2*1024*1024);
      db.transaction(foundEvent, errorCB);
     }

      function foundEvent(tx)
        {
        var TitleT = document.getElementById("texttitle").value;
       tx.executeSql("SELECT * FROM SoccerEvents WHERE Title LIKE '%" + TitleT + "%'", [], renderEvent);

                    }
       function renderEvent(tx,results) {
       if (results.rows.length > 0) {
       navigator.notification.alert("Event found");
        }
       else
        {
        navigator.notification.alert("No event!");
                        }
      }

HTML -

 <form>
            <div class="ui-field-contain">
                <label for="texttitle">Title</label>
                <input type="text" id="texttitle">
                <label for="select-native-2">Location</label>
                <select name="select-native-2" id="select-native-2" data-mini="true">
                    <option value="" disabled selected>Select your option</option>
                    <option value="1">Tower Hamlets</option>
                    <option value="2">Greenwich</option>
                    <option value="3">Islington</option>
                    <option value="4">Bromley</option>
                    <option value="4">Hackney</option>
                    <option value="4">Lewisham</option>
                </select>
                <br>
                <label for="dateD" data-position="left">Date</label>
                <input type="date" id="dateD"   />
                <br>
                <input type="submit" value="submit" onclick="return fetchEvent(); return false;">
            </div>
    </form>

2 个答案:

答案 0 :(得分:1)

表由复杂的节点树组成,因此,为了使这个过程变得舒适和简单,您可以在页面上创建Javascript生成的表,通过向您的页面插入从String生成的DOM元素,其中包含一个正常的HTML标记

有两种方法可以实现这一目标。

1

第一个:使用DOM元素的.innerHTML。

这种方法的缺点 - 在某些情况下,它会在旧IE中导致意外行为。他们在这里提到:Why does .html work and not innerHTML or appendChild必须说许多合理的公司已经放弃了对IE的支持&lt; 9,但我不得不提到这是一个缺点 - 因为你对浏览器的要求没有说明,所以这可能是你项目的重要考虑因素。

这是实现(没有bug保护 - 我跳过它以提高代码的可读性):

<!DOCTYPE html>
<html>
    <head>
        <title>Example: inserting new HTML to DOM</title>
    </head>
    <body>
        <div id="js-insert-dom-here"></div>

        <script>

            /*
            *   Input:
            *       inHtml - string that MAY contain HTML-tags
            *       inDomEl - DOM element.
            *   
            *   Result:
            *       inHtml will be inserted inside inDomEl;
            *       attention: this will rewrite all HTML
            *       that was previously situated inside inDomEl
            *   
            */
            function outputHtmlToDom( inHtml, inDomEl ) {
                inDomEl.innerHTML = inHtml;
            }

            function getOutputDiv() {
                var id = 'js-insert-dom-here';
                var div = document.getElementById( id );
                if ( div === null ) {
                    throw new Error( 'div ' + id + ' was not found on your page' );
                }
                return div;
            }

            // sugar for outputHtmlToDom
            function outputHtml( inHtml ) {
                outputHtmlToDom( inHtml, getOutputDiv() )
            }

        </script>

        <!-- example -->
        <script>

            // testing (static):
            outputHtml(
                '<b>bold</b> <i>italic</i> ' +
                '<div>div</div>' +
                '<table><tbody><tr><td>table</td></tr></tbody></table>'
            );

        </script>
        <!-- /example -->
    </body>
</html>

2

您可以使用任何从bug中抽象出来的Javascript库。我个人更喜欢jQuery来处理DOM操作的任务。

曾几何时,一个名叫John Resig的好人决定用Javascript操作DOM来创建抽象层和语法糖。他创建了jQuery。这个库的目标是从奇怪的浏览器特定的Javascript实现行为中抽象出来 - 它通过提供跨浏览器API来实现跨浏览器的行为,并且用来对抗那些隐藏在jQuery引擎下的bug。

这是网站jquery.com有一个非常好的在线文档。

这种方法的缺点 - jQuery的语法对于vanilla Javascript程序员来说是陌生的 - 所以如果你想使用它,你需要学习它,但它对于DOM操作领域来说是非常有表现力的。

你提到你使用jQueryMobile - 它需要jQuery才能工作,这意味着你的页面上包含了jQuery。

这是outputHtml的实现,使用jQuery:

<!DOCTYPE html>
<html>
    <head>
        <title>Example: inserting new HTML to DOM with jQuery</title>

        <!--
            This includes jQuery from online resourse.
            Perhaps for some applications you would want to move that to your own server
            so that you are not dependent on availability of jquery.com site.
        -->
        <script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
    </head>
    <body>
        <div id="js-insert-dom-here"></div>

        <script>
            function outputHtml( inHtml ) {
                $( '#js-insert-dom-here' ).html( inHtml );
            }
        </script>

        <!-- example -->
        <script>

            // testing (static):
            outputHtml(
                '<b>bold</b> <i>italic</i> ' +
                '<div>div</div>' +
                '<table><tbody><tr><td>table</td></tr></tbody></table>'
            );

        </script>
        <!-- /example -->
    </body>
</html>

为表格生成HTML:

现在您已了解如何将HTML插入DOM,您需要为表生成HTML。 你可以手工完成,但我建议使用专门的功能来保持可管理性。

下面,我提供了可以完成工作的示例功能代码。

您可以像这样使用它:

// actually, you should populate tableData
// with data extracted from your database
var tableData = [
    [ 'header 1',   'header 2',   'header 3'  ],
    [ '(x:1,y:1)',  '(x:2,y:1)',  '(x:3,y:1)' ],
    [ '(x:1,y:2)',  '(x:2,y:2)',  '(x:3,y:2)' ]
];

outputHtml(
    generateTableHtml( tableData )
);

generateTableHtml的代码:

<script>

    /*
    *   Purpose:
    *       Sometimes you need to generate HTML for simple table
    *       This is a helper function that does just that
    *           (simple table means that each cell spans 1 row and 1 column)
    *   
    *   Input:
    *       aasCellValues - array of arrays of strings
    *           example:
    *           [     // column      // column      // column
    *               [ 'header 1',   'header 2',   'header 3'  ], // row
    *               [ '(x:1,y:1)',  '(x:2,y:1)',  '(x:3,y:1)' ], // row
    *               [ '(x:1,y:2)',  '(x:2,y:2)',  '(x:3,y:2)' ]  // row
    *           ]
    *       
    *       bFirstIsHead - bool
    *           if === true, then first row will be rendered as Table Header
    *           default: true;
    *           
    *       bFirstIsFoot - bool
    *           if === true, then first row will be rendered as Table Footer
    *           default: false
    *       
    *   Output:
    *       String that contains HTML-markup that can be easily
    *       yanked into DOM
    *       
    *       if array is empty or aasCellValues is not array,
    *           output will return '' which is still yankable to DOM
    *   
    *   Bugs (#security):
    *       This function trusts that strings inside input array
    *           are correct and valid,
    *           thus no sanitation is performed for any of sCellValues.
    *       Thus
    *           </td> </th> </tr> </tbody> </thead> </table>
    *           provided in cell values
    *           would definely break your markup.
    *       Any Javascript would be inserted as it is was provided which will
    *           create opportunity for XSS-attack, if used with
    *           poisoned input (i.e. input from untrusted source -
    *           for example
    *               - user request,
    *               - data from database
    *           and any of that input is poisoned
    *           if it wasn't tested with criteria
    *           of purity: is it pure or not).
    *       
    *       example:
    *           [
    *               ['<' + 'script' + '>alert("Hello, XSS-attack!");</' + 'script' + '>'],
    *               ['<b onload="alert(111);">Another XSS vector</b>']
    *           ]
    *       
    *       example:
    *           [
    *               ['</table>Here breaks a table... Ruuun!!'],
    *           ]
    *       
    *       How to counter this vulnerability?
    *           Either check poisoned values before sending
    *           them to this function as input,
    *           
    *           or modify generateTableHtml code
    *           to allow another input value: function that will
    *           conduct testing for your specific purity criteria.
    *           
    */
    function generateTableHtml( aasCellValues, bFirstIsHead, bFirstIsFoot ) {
        var ou = '';

        //  you can add here error logging
        //  or alert if you feel that appropriate
        if (
            ( typeof aasCellValues === 'undefined' )
            ||
            !( aasCellValues.length > 0 )
        ) {
            return ou;
        }

        var thead = '';
        var tfoot = '';
        var tbody = '';

        // setting defaults
        if ( typeof bFirstIsHead === 'undefined' ) {
            bFirstIsHead = true;
        }
        if ( typeof bFirstIsFoot === 'undefined' ) {
            bFirstIsFoot = false;
        }

        // start of programm

        if ( bFirstIsHead || bFirstIsFoot ) {
            var firstRow = aasCellValues.shift();
            firstRow = generateTableRowHtml.th( firstRow );

            if ( bFirstIsHead ) {
                thead = '<thead>' + firstRow + '</thead>';
            }
            if ( bFirstIsFoot ) {
                tfoot = '<tfoot>' + firstRow + '</tfoot>';
            }
        }

        var i = 0;
        var L = aasCellValues.length;
        for ( var i = 0; i < L; i++ ) {
            tbody +=
                '<tr>' +
                    generateTableRowHtml.td( aasCellValues[i] ) +
                '</tr>'
            ;
        }

        if ( tbody !== '' ) {
            tbody = '<tbody>' + tbody + '</tbody>';
        }

        ou = '<table>' + thead + tfoot + tbody + '</table>';

        return ou;
    }

    // helper for function generateTableHtml
    var generateTableRowHtml = {
        th: function( asCellValues ) {
            return '<th>' + asCellValues.join('</th><th>') + '</th>';
        },
        td: function( asCellValues ) {
            return '<td>' + asCellValues.join('</td><td>') + '</td>';
        }
    }
</script>

更新:回复评论:

首先 - 如果你没有足够的JS和HTML经验来直观地知道如何适应我给你的拼图 - 那么你就陷入了困境。因为那些不能用简单的方式解释。要解释它们 - 它们需要编写/翻译几本书和一些博客。

或者您可以花一两个星期的时间进行在线教程。 -_ ^这会更具成本效益。

我有自己的生活^ ^你需要训练自己的翅膀来学习如何飞行。从长远来看,帮助太多会使我们瘫痪。因此,这是一个告别的好地方。

P.S。

获得快速结果的最佳选择是找到一些可以为您想要支持的浏览器可靠地输出WebSQL查询结果的javascript库。也许你可以在GitHub上找到类似的东西。

但是,为了完成我的开始 - 这里是如何编写代码以将请求输出到表的示例。我给你两个块:scripts + html。 Html基本上是来自您自己的列表+ div的输出表。在脚本块中 - 您将脚本放在最后一个脚本块中 - 在此实现中,您必须手动提供字段名称。脚本必须在您的表单之前 - 否则代码将无效。

我没有实施任何安全措施,因为每个项目都非常个性化。

脚本:

    <script>

        // this scriptblock allows you to use outputHtml

        /*
        *   Input:
        *       inHtml - string that MAY contain HTML-tags
        *       inDomEl - DOM element.
        *   
        *   Result:
        *       inHtml will be inserted inside inDomEl;
        *       attention: this will rewrite all HTML
        *       that was previously situated inside inDomEl
        *   
        */
        function outputHtmlToDom( inHtml, inDomEl ) {
            inDomEl.innerHTML = inHtml;
        }

        function getOutputDiv() {
            var id = 'js-result';
            var div = document.getElementById( id );
            if ( div === null ) {
                throw new Error( 'div ' + id + ' was not found on your page' );
            }
            return div;
        }

        // sugar for outputHtmlToDom
        function outputHtml( inHtml ) {
            outputHtmlToDom( inHtml, getOutputDiv() )
        }
        /*

            //basic test:
            outputHtml('<b>bold</b> <i>italic</i>');
        */

    </script>
    <script>

        // this scriptblock allows you to use generateTableHtml

        /*
        *   Purpose:
        *       Sometimes you need to generate HTML for simple table
        *       This is a helper function that does just that
        *           (simple table means that each cell spans 1 row and 1 column)
        *   
        *   Input:
        *       aasCellValues - array of arrays of strings
        *           example:
        *           [     // column      // column      // column
        *               [ 'header 1',   'header 2',   'header 3'  ], // row
        *               [ '(x:1,y:1)',  '(x:2,y:1)',  '(x:3,y:1)' ], // row
        *               [ '(x:1,y:2)',  '(x:2,y:2)',  '(x:3,y:2)' ]  // row
        *           ]
        *       
        *       bFirstIsHead - bool
        *           if === true, then first row will be rendered as Table Header
        *           default: true;
        *           
        *       bFirstIsFoot - bool
        *           if === true, then first row will be rendered as Table Footer
        *           default: false
        *       
        *   Output:
        *       String that contains HTML-markup that can be easily
        *       yanked into DOM
        *       
        *       if array is empty or aasCellValues is not array,
        *           output will return '' which is still yankable to DOM
        *   
        *   Bugs (#security):
        *       This function trusts that strings inside input array
        *           are correct and valid,
        *           thus no sanitation is performed for any of sCellValues.
        *       Thus
        *           </td> </th> </tr> </tbody> </thead> </table>
        *           provided in cell values
        *           would definely break your markup.
        *       Any Javascript would be inserted as it is was provided which will
        *           create opportunity for XSS-attack, if used with
        *           poisoned input (i.e. input from untrusted source -
        *           for example
        *               - user request,
        *               - data from database
        *           and any of that input is poisoned
        *           if it wasn't tested with criteria
        *           of purity: is it pure or not).
        *       
        *       example:
        *           [
        *               ['<' + 'script' + '>alert("Hello, XSS-attack!");</' + 'script' + '>'],
        *               ['<b onload="alert(111);">Another XSS vector</b>']
        *           ]
        *       
        *       example:
        *           [
        *               ['</table>Here breaks a table... Ruuun!!'],
        *           ]
        *       
        *       How to counter this vulnerability?
        *           Either check poisoned values before sending
        *           them to this function as input,
        *           
        *           or modify generateTableHtml code
        *           to allow another input value: function that will
        *           conduct testing for your specific purity criteria.
        *           
        */
        function generateTableHtml( aasCellValues, bFirstIsHead, bFirstIsFoot ) {
            var ou = '';

            //  you can add here error logging
            //  or alert if you feel that appropriate
            if (
                ( typeof aasCellValues === 'undefined' )
                ||
                !( aasCellValues.length > 0 )
            ) {
                return ou;
            }

            var thead = '';
            var tfoot = '';
            var tbody = '';

            // setting defaults
            if ( typeof bFirstIsHead === 'undefined' ) {
                bFirstIsHead = true;
            }
            if ( typeof bFirstIsFoot === 'undefined' ) {
                bFirstIsFoot = false;
            }

            // start of programm

            if ( bFirstIsHead || bFirstIsFoot ) {
                var firstRow = aasCellValues.shift();
                firstRow = generateTableRowHtml.th( firstRow );

                if ( bFirstIsHead ) {
                    thead = '<thead>' + firstRow + '</thead>';
                }
                if ( bFirstIsFoot ) {
                    tfoot = '<tfoot>' + firstRow + '</tfoot>';
                }
            }

            var i = 0;
            var L = aasCellValues.length;
            for ( var i = 0; i < L; i++ ) {
                tbody +=
                    '<tr>' +
                        generateTableRowHtml.td( aasCellValues[i] ) +
                    '</tr>'
                ;
            }

            if ( tbody !== '' ) {
                tbody = '<tbody>' + tbody + '</tbody>';
            }

            ou = '<table>' + thead + tfoot + tbody + '</table>';

            return ou;
        }

        // helper for function generateTableHtml
        var generateTableRowHtml = {
            th: function( asCellValues ) {
                return '<th>' + asCellValues.join('</th><th>') + '</th>';
            },
            td: function( asCellValues ) {
                return '<td>' + asCellValues.join('</td><td>') + '</td>';
            }
        }
        /*

            //basic test:
            generateTableHtml(
                [     // column      // column      // column
                    [ 'header 1',   'header 2',   'header 3'  ], // row
                    [ '(x:1,y:1)',  '(x:2,y:1)',  '(x:3,y:1)' ], // row
                    [ '(x:1,y:2)',  '(x:2,y:2)',  '(x:3,y:2)' ]  // row
                ]
            );
        */
    </script>
    <script>

        // this scriptblock allows you to use adaptRowsTo2DArrays

        function adaptRowsTo2DArrays( sqlResult, aFields ) {
            var ou = [];

            if ( ! ( sqlResult.rows.length > 0 ) ) {
                return ou;
            }

            var i = 0;
            var L_i = sqlResult.rows.length;

            var j = 0;
            var L_j = aFields.length;

            for ( i = 0; i < L_i; i++ ) {
                var tmpARow = [];
                for ( j = 0; j < L_j; j++ ) {
                    var fieldName = aFields[j];
                    tmpARow.push( sqlResult.rows[i][fieldName] );
                }
                ou.push( tmpARow );
            }

            return ou;
        }
        /*
            // basic test:
            adaptRowsTo2DArrays(
                {
                    rows: [
                        {'animalType': 'wolf', 'color': 'red+gray',           'sound': 'auuu...+rrr'   },
                        {'animalType': 'cat',  'color': 'black+white+orange', 'sound': 'meow+hisss...' }
                    ]
                },
                ['animalType', 'sound', 'color']
            );
        */

    </script>
    <script>

        // your functions:

        function fetchEvent() {
            db = window.openDatabase("SoccerEarth", "2.0", "SoccerEarthDB", 2*1024*1024);
            db.transaction(foundEvent, errorCB);
        }

        function foundEvent(tx)
        {
            var TitleT = document.getElementById("texttitle").value;
            tx.executeSql("SELECT * FROM SoccerEvents WHERE Title LIKE '%" + TitleT + "%'", [], renderEvent);
        }

        /*
            I assume that any rrow of reult consists of fields:
            'TitleT', 'LocationL', 'PeopleP', 'DateD', 'DescriptionD'
        */
        function renderEvent(tx,results) {
            if (results.rows.length > 0) {
                var aFields = ['TitleT', 'LocationL', 'PeopleP', 'DateD', 'DescriptionD'];
                var aaTable = adaptRowsTo2DArrays( adaptRowsTo2DArrays, aFields );
                var aaTable.unshift( ['Title:', 'Location:', 'People:', 'Date:', 'Description:'] )
                var tableHtml = generateTableHtml( aaTable );
                outputHtml( tableHtml );
            } else {
                navigator.notification.alert("No event!");
            }
        }

    </script>

HTML:

    <!-- insert scripts here -->

    <form>
            <div class="ui-field-contain">
                <!-- ... -->
                <input type="submit" value="submit" onclick="fetchEvent(); return false;">
            </div>
    </form>

    <div id="js-result"></div>

答案 1 :(得分:1)

感谢您的回复并回答Joan,这非常有帮助。我已经解决了这个问题,但忘了发布答案。

function foundEvent(tx) {
  var TitleT = document.getElementById("texttitle").value;
  tx.executeSql("SELECT * FROM SoccerEvents WHERE Title LIKE '%" + TitleT + "%'", [], renderEvent);
}

function renderEvent(tx, response) {
  var div = document.getElementById("responsediv");

  var temp = "<table border=\"1\"><tr><th>Title</th><th>Location</th><th>NoPeople</th><th>Date</th><th>Description</th></tr>";
  alert(response.rows.length);
  for (var i = 0; i < response.rows.length; i++) {
    temp += "<tr><td>" + response.rows.item(i).Title + "</td><td>" + response.rows.item(i).Location + "</td><td>" + response.rows.item(i).NoPeople + "</td><td>" + response.rows.item(i).Date + "</td><td>" + response.rows.item(i).Description + "</td></tr>";
    div.innerHTML = temp;
  }
}