【问题标题】:Render Template FLASK渲染模板烧瓶
【发布时间】:2019-04-24 15:41:54
【问题描述】:

当我单击用于使用 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()
        },
     });
   });

【问题讨论】:

    标签: html css ajax flask


    【解决方案1】:

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

    更简单,不是吗?

    【讨论】:

      猜你喜欢
      • 2018-03-25
      • 2021-04-02
      • 1970-01-01
      • 2018-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-12
      相关资源
      最近更新 更多