Skip to content
Myr

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

3 files+119 added−13 removed

modified:docs/patterns/jquery.rst+105 added-5 removed
4 unmodified lines
5with the DOM and JavaScript in general. It is the perfect tool to make6web applications more dynamic by exchanging JSON between server and7client.89JSON itself is a very lightweight transport format, very similar to how10Python primitives (numbers, strings, dicts and lists) look like which is11widely supported and very easy to parse. It became popular a few years12ago and quickly replaced XML as transport format in web applications.1314If you have Python 2.6 JSON will work out of the box, in Python 2.5 you15will have to install the `simplejson`_ library from PyPI.1617.. _jQuery: http://jquery.com/18.. _simplejson: http://pypi.python.org/pypi/simplejson1920Loading jQuery21--------------2223In order to use jQuery, you have to download it first and place it in the24static folder of your application and then ensure it's loaded. Ideally25you have a layout template that is used for all pages where you just have17to add two script statements to your `head` section. One for jQuery, and18one for your own script (called `app.js` here):26to add a script statement to your `head` to load jQuery:2728.. sourcecode:: html2930 <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>3233Another method is using Google's `AJAX Libraries API34<http://code.google.com/apis/ajaxlibs/documentation/>`_ to load jQuery:3536.. sourcecode:: html3738 <script type=text/javascript39 src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>4041In this case you don't have to put jQuery into your static folder, it will42instead be loaded from Google directly. This has the advantage that your43website will probably load faster for users if they were to at least one44other website before using the same jQuery version from Google because it45will already be in the browser cache. Downside is that if you don't have46network connectivity during development jQuery will not load.4748Where is My Site?49-----------------5051Do you know where your application is? If you are developing the answer
25 unmodified lines
77 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.818283JSON View Functions84-------------------8586Now let's create a server side function that accepts two URL arguments of87numbers which should be added together and then sent back to the88application in a JSON object. This is a really ridiculous example and is89something you usually would do on the client side alone, but a simple90example that shows how you would use jQuer and Flask nonetheless::9192 from flask import Flask, jsonify, render_template, request93 app = Flask(__name__)9495 @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)100101 @app.route('/')102 def index():103 return render_template('index.html')104105As you can see I also added an `index` method here that renders a106template. This template will load jQuery as above and have a little form107we can add two numbers and a link to trigger the function on the server108side.109110The HTML111--------112113You index.html template either has to extend a `layout.html` template with114jQuery loaded and the `$SCRIPT_ROOT` variable set, or do that on the top.115Here the HTML code needed for our little application (`index.html`).116Notice that we also drop the script directly into the HTML here. It is117usually a better idea to have that in a separate script file:118119.. sourcecode:: html120121 <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>139140I won't got into detail here about how jQuery works, just a very quick141explanation of the little bit of code above:1421431. ``$(function() { ... })`` specifies code that should run once the144 browser is done loading the basic parts of the page.1452. ``#('selector')`` selects an element and lets you operate on it.1463. ``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).1504. ``$.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.155156If you don't get the whole picture, download the `sourcecode157for this example158<http://github.com/mitsuhiko/flask/tree/master/examples/jqueryexample>`_159from github.
modified:examples/jqueryexample/templates/index.html+4 added-8 removed
added:examples/jqueryexample/templates/layout.html+10 added