渲染模板FLASK

时间:2019-04-23 13:43:51

标签: html css ajax flask

当我单击按钮wchich用于使用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 %}

AJAX

 $('.fby_category').click(function(e) {
    var url = "{{ url_for('main.viewchallenges') }}";
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: url,
        data: {
            'name': $(this).text()
        },
     });
   });

1 个答案:

答案 0 :(得分:0)

您要呈现一个新模板。这意味着用户将获得一个新的网页。然后,您在这里不需要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>

更简单,不是吗?