article

Friday, October 16, 2020

Simple Jquery Ajax and jsonify

 


Simple Jquery Ajax and jsonify
#app.py
from flask import Flask, render_template, jsonify

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/_get_data/', methods=['POST'])
def _get_data():
    myList = ['Element1', 'Element2', 'Element3']

    return jsonify({'data': render_template('response.html', myList=myList)})

if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <button id="btn">Click Me</button>
        <div id="response"></div>
        <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
  <script type="text/javascript">
      $('button#btn').click(function(){
        $.ajax({
            url: "/_get_data/",
            type: "POST",
            success: function(resp){
                $('div#response').append(resp.data);
            }
        });
      });
  </script>
    </body>
</html>
templates/response.html
//templates/response.html
<ul>
    {% for elem in myList %}
        <li>{{elem}}</li>
    {% endfor %}
</ul>

Related Post