javascript - Adding a context variable with AJAX in Flask -
i have select form needs populated through ajax. consider simple example:
templates/index.html
<!doctype html> <html> <body> <select id="elements"> </select> <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script> <script> $.ajax({ url: '/get-something/5', type: "get", datatype: "html", success: function (msg) { $('#elements').html(msg) } }) </script> </body> </html> app.py
from flask import flask, render_template app = flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/get-something/<int:n>') def get_something(n): result = '' in xrange(n): result += "<option value='%s'>%s</option>\n" % (i, i) return result if __name__ == '__main__': app.run(debug=true) that works fine , did. but, wondering if there exists (better?) way.
for instance, i'd prefer having context variable better separate view controller. this:
app.modified.py
@app.route('/get-something/<int:n>') def get_something(n): return dict(elements=xrange(n)) templates/index.modified.html
<select id="elements"> {% elem in elements %} <option value='{{ elem }}'>{{ elem }}</option>\n {% endfor %} </select> unfortunately, not work. says, 'dict' object not callable.
any please? possible? notice don't want reload page, want same behavior in ajax example.
using index.modified, need this:
return render_template('index.modified.html', elements=your_dictionary) not trying return dictionary (which why getting error). see http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-ii-templates fore more examples
Comments
Post a Comment