Skip to content
Myr

jquery.rst

This file

Path

docs/patterns/jquery.rst

167 lines · 6.7 KiB

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than de3b6ab point at it.

Fixed a broken sentence about blueprints.Armin Ronacherbefore adoptionde3b6ab

lines 1–167why, one step back
1AJAX with jQuery
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.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 have26to add a script statement to the bottom of your `<body>` to load jQuery:2728.. sourcecode:: html2930 <script type=text/javascript src="{{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 src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script>39 <script>window.jQuery || document.write('<script src="{{40 url_for('static', filename='jquery.js') }}">\x3C/script>')</script>4142In this case you have to put jQuery into your static folder as a fallback, but it will43first try to load it directly from Google. This has the advantage that your44website will probably load faster for users if they went to at least one45other website before using the same jQuery version from Google because it46will already be in the browser cache.4748Where 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 could answer that question for57us, but if we are using jQuery we should 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 kind enough to do the right thing here and80 escape slashes for you (``{{ "</script>"|tojson|safe }}`` is rendered as81 ``"<\/script>"``).828384JSON View Functions85-------------------8687Now let's create a server side function that accepts two URL arguments of88numbers which should be added together and then sent back to the89application in a JSON object. This is a really ridiculous example and is90something you usually would do on the client side alone, but a simple91example that shows how you would use jQuery and Flask nonetheless::9293 from flask import Flask, jsonify, render_template, request94 app = Flask(__name__)9596 @app.route('/_add_numbers')97 def add_numbers():98 a = request.args.get('a', 0, type=int)99 b = request.args.get('b', 0, type=int)100 return jsonify(result=a + b)101102 @app.route('/')103 def index():104 return render_template('index.html')105106As you can see I also added an `index` method here that renders a107template. This template will load jQuery as above and have a little form108we can add two numbers and a link to trigger the function on the server109side.110111Note that we are using the :meth:`~werkzeug.datastructures.MultiDict.get` method here112which will never fail. If the key is missing a default value (here ``0``)113is returned. Furthermore it can convert values to a specific type (like114in our case `int`). This is especially handy for code that is115triggered by a script (APIs, JavaScript etc.) because you don't need116special error reporting in that case.117118The HTML119--------120121Your index.html template either has to extend a `layout.html` template with122jQuery loaded and the `$SCRIPT_ROOT` variable set, or do that on the top.123Here's the HTML code needed for our little application (`index.html`).124Notice that we also drop the script directly into the HTML here. It is125usually a better idea to have that in a separate script file:126127.. sourcecode:: html128129 <script type=text/javascript>130 $(function() {131 $('a#calculate').bind('click', function() {132 $.getJSON($SCRIPT_ROOT + '/_add_numbers', {133 a: $('input[name="a"]').val(),134 b: $('input[name="b"]').val()135 }, function(data) {136 $("#result").text(data.result);137 });138 return false;139 });140 });141 </script>142 <h1>jQuery Example</h1>143 <p><input type=text size=5 name=a> +144 <input type=text size=5 name=b> =145 <span id=result>?</span>146 <p><a href=# id=calculate>calculate server side</a>147148I won't got into detail here about how jQuery works, just a very quick149explanation of the little bit of code above:1501511. ``$(function() { ... })`` specifies code that should run once the152 browser is done loading the basic parts of the page.1532. ``$('selector')`` selects an element and lets you operate on it.1543. ``element.bind('event', func)`` specifies a function that should run155 when the user clicked on the element. If that function returns156 `false`, the default behaviour will not kick in (in this case, navigate157 to the `#` URL).1584. ``$.getJSON(url, data, func)`` sends a `GET` request to `url` and will159 send the contents of the `data` object as query parameters. Once the160 data arrived, it will call the given function with the return value as161 argument. Note that we can use the `$SCRIPT_ROOT` variable here that162 we set earlier.163164If you don't get the whole picture, download the `sourcecode165for this example166<http://github.com/mitsuhiko/flask/tree/master/examples/jqueryexample>`_167from github.