javascript jQuery ajax 填充 html 表格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6045506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:16:31  来源:igfitidea点击:

jQuery ajax fill html table

javascriptjqueryhtml-table

提问by kralco626

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)

使用 Jquery Ajax 用包含我的数据库数据的 tr 元素填充 tbody 的最快、最有效的方法是什么?(除非你有更好的方法)

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

从网络服务返回 html 代码还是在 Javascript 中动态创建 html 代码?

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)

此外,我必须支持用户“向下钻取;即单击 > 或双击该行以打开一个窗格以显示更多信息。(包括另一个表和一些由单独的 web 服务返回的详细信息)

All ideas welcome!

欢迎所有想法!

采纳答案by pixelbobby

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

我在一个使用 jQuery 和 AJAX 的大型企业门户上工作。我已经实施jQuery Templates了,jQuery TableSorter plug-in以促进这一点。下面是一些示例代码:

Javascript (Data Provider): Data.Lists.js

Javascript(数据提供者):Data.Lists.js

myorg.data.list.GetListItems ({
    webURL: "http://our.awesome.portal.com/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)

HTML(模板)

<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 comment" title="Comments"></a>
                    </td>
                </tr>
            {{/each}}
        {{else}}
            <tr><td colspan="4">You have no projects.</td></tr>
        {{/if}}
        </tbody>
    </table>
-->
</div>

回答by Matt Ball

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...)
  • 服务器端,使用您选择的模板语言(ASP.NET、PHP、JSP、Django 模板...)或
  • 客户端,使用 JavaScript 模板($.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 consistentlythroughout your app unless there is a truly compelling reason to do otherwise.

客户端将(理论上)减少服务器上的负载,但这也可能不是相关问题。无论您选择哪种风格,您都应该在整个应用程序中始终如一地使用它,除非有真正令人信服的理由不这样做。

回答by ShaneBlake

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

您可以使用 jQuery .ajax() 调用返回 JSON 对象中的数据,并使用 .tmpl() 模板插件来呈现 html。

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

您可以在此处查看模板文档:http: //api.jquery.com/tmpl/

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

更新:我发布了一个示例作为另一个问题的答案

回答by SquidScareMe

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

从 Web 服务返回 HTML 会紧密耦合您的代码。两种方法中较好的一种是在 Javascript 中创建 HTML。

回答by Sydwell

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())

我只是从 AJAX PHP 调用中检索二维 JSONed 数组。
(使用php函数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.

请注意附加的 'json' 参数。

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.

使用标准 jQuery 可以安静地轻松操作整个表格,从添加标题行,将一个或多个行或表格转换为输入字段。

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

如果您不想,我想您不必使用 PDO 例程从数据库中获取详细信息。

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

下面是使用上面列出的技术构建的表格的图像 在此处输入图片说明