【问题标题】:Populate an html table column with data dynamically用数据动态填充 html 表格列
【发布时间】:2021-09-13 08:34:34
【问题描述】:

我有一对多的相关数据(th 和 td),在页面加载时我使用 ajax 从服务器加载数据,我如何选择每个 th(列)并用链接的数据填充它。

这是桌子:

        <table border="1" style="width: 95%;" id="table">

        <tr id="ths">
            {% for th in ths %}
            <th>
                <div data-th_id="{{ th.id }}">{{ th.name }}</div>
            </th>
            {% endfor %}
        </tr>

        <!-- populate with AJAX  -->

        <!-- <tr> 
            <td>
                <div></div>
            </td>
        </tr> -->

        <!-- END AJAX  -->

    </table>

AJAX:

    $("table tr th").each(function () {

    var th_id = $(this).children().data('th_id')

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: "/api/load_tds",
        data: JSON.stringify({
            "th_id": th_id
        }),
        success: function (res) {

            table = document.getElementById("table");

            $.each(res, function (index, value) {

            });

        }
    });

});

【问题讨论】:

  • 使用 $(this).children().attr('data-th_id');获取值和 $(this).children().attr('data-th_id', 'valuetobeplaced');用于设置值

标签: javascript html jquery flask


【解决方案1】:

希望我没听错。您想从服务器获取每列的数据,然后在正确的&lt;tr&gt; 中将其显示为&lt;td&gt;

// creating an empty table:

for (let i = 0; i < 5/* amount of columns*/; i++) {
    var $row = $('<tr/>');
    for (let a = 0; a < 5/* amount of rows*/; a++) {
        $row.append($('<td/>'));
    }
    $('table').append($row);
}

$("table tr th").each(function () {
var th_id = $(this).children().data('th_id');


$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    url: "/api/load_tds",
    data: JSON.stringify({
        "th_id": th_id
    }),
    success: function (res) {
        let th_index = 0 /* set the index of the current column */;

        // filling the nth td of each row with your data

        $.each(res, function (index, value) {
            $('table tr:nth-child(' + index + ') td:nth-child(' + th_index + ')').append('<div>' + value + '</div>');
        });
    }
});

});

由于我无法访问您的 API,因此无法测试代码,但我希望它可以工作,或者至少该原理对您有所帮助。

但是如果您只想在页面加载时从您的服务器加载数据,最好的做法是直接通过您的 Jinja2 模板传递数据。它最大限度地减少了数据传输,并且 js 代码会更干净。 直接在服务器端将数据处理到模板中总是比事后使用 Ajax 获取数据要好!

最好的问候

【讨论】:

    猜你喜欢
    • 2013-08-29
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 2018-01-11
    • 2011-10-30
    相关资源
    最近更新 更多