在jQuery AJAX请求后向Flask渲染Jinja [英] Render Jinja after jQuery AJAX request to Flask
问题描述
我有一个Web应用程序,当HTML中的 select 元素发生更改时,该应用程序会从 Flask 获取动态数据.当然,这是通过 jquery ajax 完成的.我没有这个问题.
I have a web application that gets dynamic data from Flask when a select element from HTML is changed. of course that is done via jquery ajax. No probs here I got that.
问题在于,Flask发送的动态数据-是来自数据库 Flask-sqlalchemy 的对象列表.
The problem is, the dynamic data - that is sent by Flask -, is a list of objects from the database Flask-sqlalchemy.
当然,数据是从烧瓶作为 JSON 发送的.
Of course the data is sent as JSON from Flask.
我想使用 Jinja 遍历这些对象以显示其信息.
I'd like to iterate through those objects to display their info using Jinja.
<select id="#mySelect">
<option value="option1" id="1">Option 1 </option>
<option value="option2" id="1">Option 2 </option>
<option value="option3" id="3">Option 3 </option>
</select>
jQuery
$('body').on('change','#mySelect',function(){
var option_id = $('#mySelect').find(':selected').attr('id');
$.ajax({
url: "{{ url_for('_get_content') }}",
type: "POST",
dataType: "json",
data: {'option_id':option_id},
success: function(data){
data = data.data;
/* HERE I WANT TO ITERATE THROUGH THE data LIST OF OBJECTS */
}
});
});
烧瓶
@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': all_options})
PS:我知道jinja首先被渲染,因此无法将jQuery变量分配给Jinja.那么,如果我不能在Jinja中使用它,那么我该如何遍历数据列表呢?
推荐答案
好的,我明白了.
简而言之,我制作了一个外部 html 文件,并向其中添加了所需的 jinja 模板.
Simply, I made an external html file and added the required jinja template to it.
{% for object in object_list %}
{{object.name}}
{% endfor %}
然后在我的 Flask 文件中,我从字面上返回了 jquery 的 render_template 响应(其中包含 HTML 我想附加)
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)}
然后只需将响应中的HTML附加到要更新的div上即可.
And then simply append the HTML from the response to the required div to be updated.
这篇关于在jQuery AJAX请求后向Flask渲染Jinja的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!