Finished jQuery example documentation.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 6e2be6a · Browse files · 3 files·+119 added−13 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+119 added−13 removed
- other:+119 added−13 removed
Provenance
- Commit
a99e408- Tree
9fe6933- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
6e2be6a
3 files changed+119 added−13 removed
modified:docs/patterns/jquery.rst+105 added-5 removed
4 unmodified lines5 with the DOM and JavaScript in general. It is the perfect tool to make6 web applications more dynamic by exchanging JSON between server and7 client.8 9+JSON itself is a very lightweight transport format, very similar to how10+Python primitives (numbers, strings, dicts and lists) look like which is11+widely supported and very easy to parse. It became popular a few years12+ago and quickly replaced XML as transport format in web applications.13+14+If you have Python 2.6 JSON will work out of the box, in Python 2.5 you15+will have to install the `simplejson`_ library from PyPI.16+17 .. _jQuery: http://jquery.com/18+.. _simplejson: http://pypi.python.org/pypi/simplejson19 20 Loading jQuery21 --------------22 23 In order to use jQuery, you have to download it first and place it in the24 static folder of your application and then ensure it's loaded. Ideally25 you have a layout template that is used for all pages where you just have17-to add two script statements to your `head` section. One for jQuery, and18-one for your own script (called `app.js` here):26+to add a script statement to your `head` to load jQuery:27 28 .. sourcecode:: html29 30 <script type=text/javascript src="{{23- url_for('static', filename='jquery.js') }}"></script>24- <script type=text/javascript src="{{25- url_for('static', filename='app.js') }}"></script>31+ url_for('static', filename='jquery.js') }}"></script>32 33+Another method is using Google's `AJAX Libraries API34+<http://code.google.com/apis/ajaxlibs/documentation/>`_ to load jQuery:35+36+.. sourcecode:: html37+38+ <script type=text/javascript39+ src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>40+41+In this case you don't have to put jQuery into your static folder, it will42+instead be loaded from Google directly. This has the advantage that your43+website will probably load faster for users if they were to at least one44+other website before using the same jQuery version from Google because it45+will already be in the browser cache. Downside is that if you don't have46+network connectivity during development jQuery will not load.47+48 Where is My Site?49 -----------------50 51 Do you know where your application is? If you are developing the answer25 unmodified lines77 will not be parsed. Everything until ``</script>`` is handled as script.78 This also means that there must never be any ``</`` between the script79 tags. ``|tojson`` is kindly enough to do the right thing here and80 escape backslashes for you.81+82+83+JSON View Functions84+-------------------85+86+Now let's create a server side function that accepts two URL arguments of87+numbers which should be added together and then sent back to the88+application in a JSON object. This is a really ridiculous example and is89+something you usually would do on the client side alone, but a simple90+example that shows how you would use jQuer and Flask nonetheless::91+92+ from flask import Flask, jsonify, render_template, request93+ app = Flask(__name__)94+95+ @app.route('/_add_numbers')96+ def add_numbers():97+ a = request.args.get('a', 0, type=int)98+ b = request.args.get('b', 0, type=int)99+ return jsonify(result=a + b)100+101+ @app.route('/')102+ def index():103+ return render_template('index.html')104+105+As you can see I also added an `index` method here that renders a106+template. This template will load jQuery as above and have a little form107+we can add two numbers and a link to trigger the function on the server108+side.109+110+The HTML111+--------112+113+You index.html template either has to extend a `layout.html` template with114+jQuery loaded and the `$SCRIPT_ROOT` variable set, or do that on the top.115+Here the HTML code needed for our little application (`index.html`).116+Notice that we also drop the script directly into the HTML here. It is117+usually a better idea to have that in a separate script file:118+119+.. sourcecode:: html120+121+ <script type=text/javascript>122+ $(function() {123+ $('a#calculate').bind('click', function() {124+ $.getJSON($SCRIPT_ROOT + '/_add_numbers', {125+ a: $('input[name="a"]').val(),126+ b: $('input[name="b"]').val()127+ }, function(data) {128+ $("#result").text(data.result);129+ });130+ return false;131+ });132+ });133+ </script>134+ <h1>jQuery Example</h1>135+ <p><input type=text size=5 name=a> +136+ <input type=text size=5 name=b> =137+ <span id=result>?</span>138+ <p><a href=# id=calculate>calculate server side</a>139+140+I won't got into detail here about how jQuery works, just a very quick141+explanation of the little bit of code above:142+143+1. ``$(function() { ... })`` specifies code that should run once the144+ browser is done loading the basic parts of the page.145+2. ``#('selector')`` selects an element and lets you operate on it.146+3. ``element.bind('event', func)`` specifies a function that should run147+ when the user clicked on the element. If that function returns148+ `false`, the default behaviour will not kick in (in this case, navigate149+ to the `#` URL).150+4. ``$.getJSON(url, data, func)`` sends a `GET` request to `url` and will151+ send the contents of the `data` object as query parameters. Once the152+ data arrived, it will call the given function with the return value as153+ argument. Note that we can use the `$SCRIPT_ROOT` variable here that154+ we set earlier.155+156+If you don't get the whole picture, download the `sourcecode157+for this example158+<http://github.com/mitsuhiko/flask/tree/master/examples/jqueryexample>`_159+from github.modified:examples/jqueryexample/templates/index.html+4 added-8 removed
12345612389456789101112131415161718192021<!doctype html><title>jQuery Example</title><script type=text/javascript src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script><script type=text/javascript src="{{ url_for('static', filename='app.js') }}"></script>{% extends "layout.html" %}{% block body %}<script type=text/javascript> var $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
$(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>{% endblock %}added:examples/jqueryexample/templates/layout.html+10 added
12345678910<!doctype html><title>jQuery Example</title><script type=text/javascript src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script><script type=text/javascript src="{{ url_for('static', filename='app.js') }}"></script><script type=text/javascript> var $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};</script>{% block body %}{% endblock %}