A look at using Ajax in Flask.
On the client-side jQuery getJSON() which do a Ajax call to the function.
Here a Pen skeleton of how it look,
button when push will get value from the Python function.
Setup style.css is unchanged copy from Pen.
Folders.
In Browser http://127.0.0.1:5000/
Quote:AJAX is a developer's dream, because you can:On the server-side we have a Python function that return a random language from a list.
- Update a web page without reloading the page
- Request data from a server - after the page has loaded
- Receive data from a server - after the page has loaded
- Send data to a server - in the background
lst = ["Python", 'HTML', 'JavaScript', 'CSS']All communication is in Json format,function is returning value with Flask jsonify()
On the client-side jQuery getJSON() which do a Ajax call to the function.
Here a Pen skeleton of how it look,
button when push will get value from the Python function.
Setup style.css is unchanged copy from Pen.
Folders.
language\ app.py templates\ index.html static\ css\ style.cssapp.py
from flask import Flask, render_template, jsonify import random app = Flask(__name__) @app.route('/') def foo(): return render_template("index.html") @app.route('/get_word') def languages(): '''Return data in json format''' lst = ["Python", 'HTML', 'JavaScript', 'CSS'] words = {} words['choice'] = random.choice(lst) return jsonify(words) if __name__ == '__main__': app.run(debug=True)index.html
<!doctype html> <html> <head> <link rel=stylesheet type=text/css href="{{ url_for('static', filename='css/style.css') }}" /> <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> </head> <script type="text/javascript"> $(document).ready(function() { $("#get_data").click(function() { $.getJSON('/get_word', function(dat) { $("#language").text(dat['choice']); }); }); }); </script> <div class='all'> <div class="parent"> <h1>Ajax call</h1> <div class="one"> <button id='get_data'>Language</button> </div> <div class="two"> <a id="language">Get Language</a> </div> </div> </div> </html>Run python app.py
In Browser http://127.0.0.1:5000/