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.
The problem is, the dynamic data - that is sent by Flask -, is a list of objects from the database Flask-sqlalchemy.
Of course the data is sent as JSON from Flask.
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>
$('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})
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With