jquery - 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 的回答,它奏效了!
解决方案
如何迭代这样的客户:
<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 的元素。
推荐阅读
- javascript - 获取 node.js 中的最后一个插入 id 并将其传递给第二个查询
- auto-increment - gorm在createtable时不支持设置autoIncrement标志?
- c# - 如何使用 c# 读取此代码覆盖率 xml 文件报告
- mongodb - 来自 MongoCharts 的 NODE JS + Mongodb 聚合管道
- python - 没有为任何变量提供梯度:['dense/kernel:0', 'dense/bias:0', 'dense_1/kernel:0', 'dense_1/bias:0', 'dense_2/kernel:0', 'dense_2 /偏见:0']
- google-sheets - 数据没有通过查询在谷歌表中被标记
- python-3.x - 如何修复“AttributeError:‘ImmutableDenseNDimArray’对象没有属性‘as_real_imag’”
- nginx - 有没有办法在 nginx conf 中为 http2_push 编写正则表达式?
- java - 在 docker swarm 中的数据库之后运行 Spring Boot 服务
- r - Slurm作业数组错误:slurmstepd:错误:execve():Rscript:没有这样的文件或目录