Skip to content
Myr

jquery.rst

This file

Path

docs/patterns/jquery.rst

159 lines · 6.2 KiB

Last changed by

With -> with in headlineArmin Ronacherbefore adoptionf878919

History of this file

Take it

With -> with in headlineArmin Ronacherbefore adoptionf878919

line 1why, one step back
1AJAX with jQuery

Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a

lines 2–8why, one step back
2================
34`jQuery`_ is a small JavaScript library commonly used to simplify working5with the DOM and JavaScript in general. It is the perfect tool to make6web applications more dynamic by exchanging JSON between server and7client.8

Finished jQuery example documentation.Armin Ronacherbefore adoptiona99e408

lines 9–16why, one step back
9JSON itself is a very lightweight transport format, very similar to how
10Python 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.16

Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a

line 17why, one step back
17.. _jQuery: http://jquery.com/

Finished jQuery example documentation.Armin Ronacherbefore adoptiona99e408

line 18why, one step back
18.. _simplejson: http://pypi.python.org/pypi/simplejson

Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a

lines 19–25why, one step back
19
20Loading 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 have

Finished jQuery example documentation.Armin Ronacherbefore adoptiona99e408

line 26why, one step back
26to add a script statement to your `head` to load jQuery:

Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a

lines 27–30why, one step back
27
28.. sourcecode:: html2930 <script type=text/javascript src="{{

Finished jQuery example documentation.Armin Ronacherbefore adoptiona99e408

line 31why, one step back
31 url_for('static', filename='jquery.js') }}"></script>

Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a

line 32why, one step back
32

Finished jQuery example documentation.Armin Ronacherbefore adoptiona99e408

lines 33–47why, one step back
33Another method is using Google's `AJAX Libraries API
34<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.47

Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a

lines 48–80why, one step back
48Where is My Site?
49-----------------5051Do you know where your application is? If you are developing the answer52is quite simple: it's on localhost port something and directly on the root53of that server. But what if you later decide to move your application to54a different location? For example to ``http://example.com/myapp``? On55the server side this never was a problem because we were using the handy56:func:`~flask.url_for` function that did could answer that question for57us, but if we are using jQuery we should better not hardcode the path to58the application but make that dynamic, so how can we do that?5960A simple method would be to add a script tag to our page that sets a61global variable to the prefix to the root of the application. Something62like this:6364.. sourcecode:: html+jinja6566 <script type=text/javascript>67 $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};68 </script>6970The ``|safe`` is necessary so that Jinja does not escape the JSON encoded71string with HTML rules. Usually this would be necessary, but we are72inside a `script` block here where different rules apply.7374.. admonition:: Information for Pros7576 In HTML the `script` tag is declared `CDATA` which means that entities77 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.

Finished jQuery example documentation.Armin Ronacherbefore adoptiona99e408

lines 81–159why, one step back
81
8283JSON 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.