最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery ajax fill html table - Stack Overflow

programmeradmin4浏览0评论

If I have a table:

<table>
    <thead>
        <tr>Col1</tr>
        <tr>Col2</tr>
        <tr>Col3</tr>
    </thead>
    <tbody>
    </tbody>
</table>

What is the fastest, most efficient way to fill the tbody with tr elements containing my data from a database using a Jquery Ajax. (unless you have a better way)

Return html code from the webservice OR dynamically create the html code in Javascript?

Also I have to support the user "drilling down; i.e. either clicking a > or double clicking the row to open a pane to show some more information. (including another table and some detail information returned by a separate webservice)

All ideas wele!

If I have a table:

<table>
    <thead>
        <tr>Col1</tr>
        <tr>Col2</tr>
        <tr>Col3</tr>
    </thead>
    <tbody>
    </tbody>
</table>

What is the fastest, most efficient way to fill the tbody with tr elements containing my data from a database using a Jquery Ajax. (unless you have a better way)

Return html code from the webservice OR dynamically create the html code in Javascript?

Also I have to support the user "drilling down; i.e. either clicking a > or double clicking the row to open a pane to show some more information. (including another table and some detail information returned by a separate webservice)

All ideas wele!

Share Improve this question edited Sep 16, 2018 at 21:29 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked May 18, 2011 at 13:28 kralco626kralco626 8,64441 gold badges115 silver badges171 bronze badges 1
  • 1 I suggest using the jquery template plugin for inserting the data into the table. – bigblind Commented May 18, 2011 at 13:44
Add a ment  | 

5 Answers 5

Reset to default 3

Unless you need to create literally thousands of rows, performance is just not a concern here. Where you generate the markup is really a design decision. You can generate the markup:

  • Server-side, in your templating language of choice (ASP.NET, PHP, JSP, Django templates...) or
  • Client-side, using JavaScript templates ($.tmpl, Mustache...)

Client side will (theoretically) decrease the load on your server, but this too is likely not a relevant issue. Whichever flavor you choose, you should use that consistently throughout your app unless there is a truly pelling reason to do otherwise.

I work on a large-scale enterprise portal that uses jQuery and AJAX. I've implemented jQuery Templates and the jQuery TableSorter plug-in to facilitate this. Here's some example code:

Javascript (Data Provider): Data.Lists.js

myorg.data.list.GetListItems ({
    webURL: "http://our.awesome.portal./Lists",
    listName: "Projects List",
    caml: caml,
    CAMLRowLimit: 6,
    callback: function(data) {
        var list = {};
        //code here that formats some data before binding
        list.items = data;
        var templateHtml = $('.ptMyProjects').html()
        .replace("<!--", "").replace("-->","");
        var html = $.tmpl(templateHtml, list);
        $('.ptMyProjects').html(html);
        //make sortable table
        $('.ptMyProjects .tablesorter').tablesorter({
            sortList: [[0,0]],
            headers: {3: {sorter: false}},
            widgets: ['zebra']
        });
        //class last row
        $('.ptMyProjects .tablesorter thead th').last().addClass('last');
        //add hover effect
        $('.ptMyProjects .tablesorter tbody tr, .tablesorter thead .header').hover(function(){
            $(this).addClass('hover');
        }, function(){
            $(this).removeClass('hover');
        });
        //add tooltips
        $('.ptMyProjects .vg_icon').tipsy({gravity: 's'});
    }
});

HTML (the template)

<div class="ptMyProjects ptTemplate">
    <!--
    <table class="tablesorter" border="0" cellpadding="0" cellspacing="0">
        <thead>
            <tr class="gradient_gray">
                <th>Title</th>
                <th>Status</th>
                <th style="border-right: none;">Progress</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
        {{if items.length > 0}}
            {{each items}}
                <tr class='item' recordid="${ows_ID}">
                    <td ><a class='{{if ows_Critical_x0020_Project == "1"}}critical{{/if}}' href="${DisplayURL}">${ows_Title}</a> </td>
                    <td class="status">
                        <a href="#" class="pstatus">${ows_ProjStatus}</a>
                        <div style='display: none;'>
                            {{if ows_ProjComments}}
                                <div style="padding-bottom: 10px;">${ows_ProjComments}</div>
                            {{/if}}
                            <div style="font-weight: bold;">Lasted Edited By ${Editor}</div>
                            <div style="font-style: italic;">${when}</div>
                        </div>
                    </td>
                    <td>
                    <div class="ui-widget-default">
                        <div class="progressbar" value="${ows_PercentComplete}" style="height:100%;"></div>
                    </div>
                    </td>
                    <td class="actions">
                        {{if ows_ProjStatus != "Completed"}}<a href="#" class="vg_icon tick" title="Mark Completed"></a>{{/if}}
                        <a href="${EditURL}" class="vg_icon pencil" title="Edit"></a>
                        <a href="#" class="vg_icon ment" title="Comments"></a>
                    </td>
                </tr>
            {{/each}}
        {{else}}
            <tr><td colspan="4">You have no projects.</td></tr>
        {{/if}}
        </tbody>
    </table>
-->
</div>

Returning HTML from the webservice tightly couples your code. The better of the two ways is to create the HTML in Javascript.

You can use jQuery .ajax() call to return the data in a JSON object and use the .tmpl() templating plugin to render the html.

You can view the templating documentation here : http://api.jquery./tmpl/

Update: I posted an example as an answer to another question

This solution works extremely well for me.

I simply retrieve a two dimension JSONed array from an AJAX PHP call.
(Using the php function json_encode())

Then simply iterate over the array to construct insertable table rows. as shown here.

$.post("./pdo_select.php", {post_query : view_q }, function(data) {
            var textToInsert = '';
            $.each(data, function(row, rowdata) {
               textToInsert += '<tr>';
               $.each(rowdata, function (ele, eledata){
                  textToInsert  += '<td>' + eledata + '</td>';
               });
               textToInsert += '</tr>';
            });
            $("#questions_table").append(textToInsert);

}, 'json'); 

Note the additional 'json' parameter.

The whole table can be quiet easily manipulated with standard jQuery, from adding a header row, turning one or more rows or tables into input fields.

I guess you don't have to use PDO routines to obtain the details from the database if you don't want to.

Below is a image of a table constructed using the technique listed above

发布评论

评论列表(0)

  1. 暂无评论