日課書

编程100小时挑战

AJAX with jQuery in Flask

  1. Loading jQuery
1
2
<script type=text/javascript src="{{
url_for('static', filename='jquery.js') }}">
</script>

or

1
2
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="{{url_for('static', filename='jquery.js') }}">\x3C/script>')</script>

  1. Get URL Root
1
2
3
<script type=text/javascript>
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
</script>

  1. JSON View Functions
1
2
3
4
5
6
7
8
9
10
11
12
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)

@app.route('/_add_numbers')
def add_numbers():
a = request.args.get('a', 0, type=int)
b = request.args.get('b', 0, type=int)
return jsonify(result=a + b)

@app.route('/')
def index():
return render_template('index.html')
  1. The HTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script type=text/javascript>
$(function() {
$('a#calculate').bind('click', function() {
$.getJSON($SCRIPT_ROOT + '/_add_numbers', {
a: $('input[name="a"]').val(),
b: $('input[name="b"]').val()
}, function(data) {
$("#result").text(data.result);
});
return false;
});
});
</script>

<h1>jQuery Example</h1>
<p><input type=text size=5 name=a> +
<input type=text size=5 name=b> =
<span id=result>?</span>
<p><a href=# id=calculate>calculate server side</a>

Flask/Docs/AJAX with jQuery