Render Jinja after jQuery AJAX request to Flask

≡放荡痞女 提交于 2019-12-02 21:22:15

Okay, I got it.

Simply, I made an external html file and added the required jinja template to it.

{% for object in object_list %}
   {{object.name}}
{% endfor %}

then in my Flask file I literally returned the render_template response to the jquery ( which contained the HTML I wanted to append )

objects_from_db = getAllObjects()
return jsonify({'data': render_template('the_temp.html', object_list=objects_from_db)}

And then simply append the HTML from the response to the required div to be updated.

If you are sending data using json you don't need to use Jinja2. You can simply try something like this:

@app.route('/_get_content/')
def _get_content():
    option_id = request.form['option_id']
    all_options = models.Content.query.filter_by(id=option_id)
    return jsonify({'data': [option.name for option in all_options]})

or define a method in your model something like to_json that returns a field or dictionary or ... and call it in your view.

@app.route('/_get_content/')
def _get_content():
    option_id = request.form['option_id']
    all_options = models.Content.query.filter_by(id=option_id)
    return jsonify({'data': [option.to_json() for option in all_options]})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!