需要帮助使用 JQuery 将新数据放入表中

Need help put new data in the table, using JQuery

本文关键字:数据 新数据 帮助 JQuery      更新时间:2023-09-26

我对JS和客户端非常陌生,请帮助我实现这一目标:

每次我将主题添加到数据库时,我希望它出现在表中。

.html

    {% block main-menu %}
        <h3>Existing Subjects</h3>
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Documents</th>
                    <th>Followers</th>
                    <th>Created</th>
                    <th>Updated</th>
                    <th>Posted By</th>
                </tr>
            <tbody>
            {% if subjects %}
                    <tr id="subject-description-main-menu-list">
                        <th id="subject-name"></th>
                        <th id="subject-docs"></th>
                        <th id="subject-followers"></th>
                        <th id="subject-created"></th>
                        <th id="subject-updated"></th>
                        <th id="subject-posted-by"></th>
                    </tr>
            {% endif %}
            </tbody>
        </table>
    {% endblock %}

这是我的Jquery:

function fill_subject_table_in_main_content() {
    $("#subject-description-main-menu-list").text('');
    $.get("/subject/list/", function(data){
        var FIELDS = ['name', 'num_of_followers', 'created_time', "created_by"];
        for( var i=0; i<data.length; i++) {
            for ( var j=0; j<FIELDS.length; j++) {
                $("#subject-description-main-menu-list").append('<th>'+data[i]['fields'][FIELDS[j]]+'</th>');
            }
        };
    }, 'json');
}

我通过 get 方法获得的数据是正确的,但它出现在一行中.....但我希望它像一张桌子...

现在它看起来像这样:

Existing Subjects
Name    Documents   Followers   Created                           Updated   Posted By
Math 140       NONE             1         2012-08-17 08:04:02      NONE       r English 102 1   2012-08-17 08:04:14 r

首先,您将标头标签附加到表中。你会想要"td"。其次,你在$("#subject-description-main-menu-list")上调用.append,这是一行。您应该将行追加到表中,并将数据追加到每一行。

像这样:

for( var i=0; i<data.length; i++) {
var newRow = document.createElement("tr");
for ( var j=0; j<FIELDS.length; j++) {
    $(newRow).append('<td>'+data[i]['fields'][FIELDS[j]]+'</td>');
}
$("#yourTableId").append(newRow);

};