[Flask]Ajax in Flask - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: Tutorials (https://python-forum.io/forum-4.html) +---- Forum: Web Tutorials (https://python-forum.io/forum-35.html) +---- Thread: [Flask]Ajax in Flask (/thread-189.html) |
[Flask]Ajax in Flask - snippsat - Sep-28-2016 A look at using Ajax in Flask. 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. 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/ RE: Flask and Ajax - wavic - Sep-29-2016 Hello! There is AJAX extension for Flask. Here are some other Flask extensions you can find useful. RE: Flask and Ajax - snippsat - Sep-29-2016 (Sep-29-2016, 12:26 PM)wavic Wrote: Hello!Yes,i know this. I find using jQuery direct to be cleaner in many cases, if there are not so many Ajax call. There are some setup work to do when using Sijax. |