html - 渲染模板烧瓶
问题描述
当我单击用于使用 ajax 脚本过滤数据的按钮时,我遇到了重新加载页面的问题。在条件 IF 不工作渲染模板。下面的示例代码
Python
def viewchallenges():
categories = Categories.query.all()
if request.method=='POST':
category_id=Categories.query.filter_by(category=request.form['name']).first()
check=Challenge.query.filter_by(categorie_id=category_id.id).order_by(Challenge.timestamp.desc()).all()
if not check:
flash(_('not found'))
else:
page = request.args.get('page', 1, type=int)
posts = Challenge.query.filter_by(categorie_id=category_id.id).order_by(Challenge.timestamp.desc()).paginate(
page, current_app.config['POSTS_PER_PAGE'], False)
next_url = url_for('main.viewchallenges', page=posts.next_num) \
if posts.has_next else None
prev_url = url_for('main.viewchallenges', page=posts.prev_num) \
if posts.has_prev else None
return render_template('viewChallanges.html', title=_('View Challenge'), posts=posts.items, next_url=next_url, prev_url=prev_url,categories=categories)
page = request.args.get('page', 1, type=int)
posts =Challenge.query.order_by(Challenge.timestamp.desc()).paginate(
page,current_app.config['POSTS_PER_PAGE'], False)
next_url = url_for('main.viewchallenges', page=posts.next_num) \
if posts.has_next else None
prev_url = url_for('main.viewchallenges', page=posts.prev_num) \
if posts.has_prev else None
return render_template('viewChallanges.html', title=_('View Challenge'), posts=posts.items, next_url=next_url, prev_url=prev_url,categories=categories)
HTML
{% for item_category in categories %}
<button class="btn btn-secondary fby_category">{{item_category.category}}</button>
{% endfor %}
阿贾克斯
$('.fby_category').click(function(e) {
var url = "{{ url_for('main.viewchallenges') }}";
e.preventDefault();
$.ajax({
type: "POST",
url: url,
data: {
'name': $(this).text()
},
});
});
解决方案
你想渲染一个新的模板。这意味着用户将获得一个新网页。那么你在这里不需要Javascript。您可以创建多个表单
{% for item_category in categories %}
<form action="{{ url_for('main.viewchallenges') }}" method="post">
<input type="submit" name="{{item_category.category}}<" value="
{{item_category.category}}" />
{% endfor %}
</form>
更容易,不是吗?
推荐阅读
- python - 将 bfill 与所选数字一起使用
- python - 为什么我在尝试在 Keras 中构建具有多个输入的架构时会出错?
- excel - 查找并偏移以将值复制到第二个工作表的末尾
- java - HashMap 到 Json 数组对象 - Java
- java - C# 从 Java AES/CBC/PKCS5Padding 加密/解密
- docker - Docker 镜像名称自动更改
- mysql - 为什么我不能通过docker使用密码登录mysql服务器?
- algorithm - 卡在 Djikstra 算法上
- bash - 在 bash 中,脚本引用另一个脚本的路径的最佳方式是什么?
- jpa - 使用 JPA 在数据库中创建表外键约束