ajax flask jinja,在向Flask發出jQuery AJAX請求后渲染Jinja

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.

我有一個Web應用程序,當HTML中的select元素發生更改時,它會從Flask獲取動態數據。當然這是通過jquery ajax完成的。沒有probs在這里我得到了。

The problem is, the dynamic data - that is sent by Flask -, is a list of objects from the database Flask-sqlalchemy.

問題是,Flask發送的動態數據是Flask-sqlalchemy數據庫中的對象列表。

Of course the data is sent as JSON from Flask.

當然,數據是從Flask發送的JSON。

I'd like to iterate through those objects to display their info using Jinja.

我想迭代這些對象以使用Jinja顯示它們的信息。

HTML

Option 1

Option 2

Option 3

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 */

}

});

});

Flask

@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 : I know that jinja gets rendered first so there is no way to assign jQuery variables to Jinja. So how exactly am I going to iterate through the data list if I can't use it in Jinja ?

2 个解决方案

#1

7

Okay, I got it.

好的,我明白了。

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

簡單地說,我制作了一個外部html文件並添加了所需的jinja模板。

{% 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 )

然后在我的Flask文件中,我逐字地將render_template響應返回給jquery(其中包含我想要追加的HTML)

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.

然后只需將響應中的HTML附加到要更新的所需div即可。

#2

0

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

如果您使用json發送數據,則不需要使用Jinja2。你可以嘗試這樣的事情:

@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.

或者在模型中定義類似於to_json的方法,該方法返回字段或字典或...並在視圖中調用它。

@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]})