首页 > 解决方案 > Jquery遍历传递给模板的烧瓶数据

问题描述

我想使用 jquery 遍历通过 render_template 传递给模板的烧瓶数据库查询结果,并将数据逐行添加到 html 表中。我想不出正确的 jquery 命令来使它工作!当我运行代码时,它不会抛出任何错误,它只是显示一个空表。db 表中有 2 条记录。

数据库模型:

class Cust(db.Model):
    __tablename__ = 'custs'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), index=True, nullable=False)
    age = db.Column(db.Integer, nullable=False)

烧瓶视图:

@home.route('/')
def homepage():
    custs = Cust.query.all()
    return render_template('home/index.html', title="Home", custs=custs)

模板:

<div class="container-fluid">
  <table class="table" id="table1">
    <thead>
      <tr>
        <th>Name</th>
        <th>Age</th>
      </tr>  
    </thead>
    <tbody>
      <tr></tr>
    </tbody>
  </table>
</div>

<script type="text/javascript">

  $(function() {
    var i = 0;
    while (i < '{{ custs|length }}') {
        var name = custs[i].name;
        var age = custs[i].age;
        $('#table1 > tbody:last-child').append('<tr><td>' + name + '</td><td>' + age + '</td></tr>');
        i++;
    } 
});

</script>

但是,如果我将脚本运行为:

$(function() {
            var name = custs[0].name;
            var age = custs[0].age;
            $('#table1 > tbody:last-child').append('<tr><td>' + name + '</td><td>' + age + '</td></tr>');
    });

我的表将填充第一条记录!

好的,对于可能遇到此问题的其他人,这就是我的做法!

$(function() {
    {% for c in custs %}
        var name = '{{ c.name }}';
        var age = '{{ c.age }}';
        $('#table1 > tbody').append('<tr><td>' + name + '</td><td>' + age + '</td></tr>');
    {% endfor %}
});

它现在遍历查询变量并将数据正确加载到表中。

感谢@Kata Csortos 的回答,它奏效了!

标签: jqueryflask

解决方案


如何迭代这样的客户:

<script type="text/javascript">

  $(function() {
    for (const cust of custs) {
        const name = cust.name;
        const age = cust.age;
        $('#table1 > tbody:last-child').append('<tr><td>' + name + '</td><td>' + age + '</td></tr>');
    } 
});

</script>

或者将 custs 的长度作为变量传递给 jinja,并使用 for 循环遍历 custs 的元素。


推荐阅读