Created
March 13, 2020 17:55
-
-
Save mosdevly/c8555189cc634c58b60e05e7fbe82ebc to your computer and use it in GitHub Desktop.
Flask with jQuery API Request Demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% extends 'base.html' %} | |
{% block content %} | |
<script src="{{ url_for('static', filename='js/example.js') }}"></script> | |
<div id="users"> | |
</div> | |
{% endblock %} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function() { | |
const userDiv = $('#users'); | |
$.get('api/users', (res) => { | |
for (user of res) { | |
console.log(user); | |
userDiv.append(`<li>${user.username}</li>`); | |
} | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@app.route('/example') | |
def example(): | |
"""Example of using sqlalchemy to return JSON.""" | |
return render_template('example.html') | |
@app.route('/api/users') | |
def get_all_users(): | |
"""Example of using sqlalchemy to return JSON.""" | |
users = User.query.all() | |
return jsonify([u.serialize() for u in users]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code assumes a
base.html
which had a head which includes a script tag to the jQuery CDN! Edit: it needs to be the full uncompressed version of jQuery.It also assumes you need to serialize the sqlalchemy models. Here's an example of how you can do that: