Skip to content
Myr

jquery.rst

This file

Path

docs/patterns/jquery.rst

167 lines · 6.7 KiB

Last changed by

Merge branch 'master' into blueprintsArmin Ronacherbefore adoption2d946b9

History of this file

Take it

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

Added some whitespaceArmin Ronacherbefore adoption2912ff6

lines 1–25why, 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 have

Merge branch 'master' into blueprintsArmin Ronacherbefore adoption2d946b9

line 26why, one step back
26to add a script statement to the bottom of your `<body>` to load jQuery:

Added some whitespaceArmin Ronacherbefore adoption2912ff6

lines 27–37why, one step back
27
28.. 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:: html37

Merge branch 'master' into blueprintsArmin Ronacherbefore adoption2d946b9

lines 38–40why, one step back
38 <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>

Added some whitespaceArmin Ronacherbefore adoption2912ff6

line 41why, one step back
41

Merge branch 'master' into blueprintsArmin Ronacherbefore adoption2d946b9

lines 42–43why, one step back
42In this case you have to put jQuery into your static folder as a fallback, but it will
43first try to load it directly from Google. This has the advantage that your

Added some whitespaceArmin Ronacherbefore adoption2912ff6

lines 44–45why, one step back
44website will probably load faster for users if they went to at least one
45other website before using the same jQuery version from Google because it

Merge branch 'master' into blueprintsArmin Ronacherbefore adoption2d946b9

line 46why, one step back
46will already be in the browser cache.

Added some whitespaceArmin Ronacherbefore adoption2912ff6

lines 47–55why, one step back
47
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 handy

Fix some typos in the docsjgraemebefore adoptionff2786d

lines 56–57why, one step back
56:func:`~flask.url_for` function that could answer that question for
57us, but if we are using jQuery we should not hardcode the path to

Added some whitespaceArmin Ronacherbefore adoption2912ff6

lines 58–110why, one step back
58the 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.110

fixing cross-referenced links on jquery patterns pagematt swansonbefore adoption5764f3a

line 111why, one step back
111Note that we are using the :meth:`~werkzeug.datastructures.MultiDict.get` method here

Added some whitespaceArmin Ronacherbefore adoption2912ff6

lines 112–120why, one step back
112which 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--------120

Fix some typos in the docsjgraemebefore adoptionff2786d

line 121why, one step back
121Your index.html template either has to extend a `layout.html` template with

Added some whitespaceArmin Ronacherbefore adoption2912ff6

line 122why, one step back
122jQuery loaded and the `$SCRIPT_ROOT` variable set, or do that on the top.

Fix some typos in the docsjgraemebefore adoptionff2786d

line 123why, one step back
123Here's the HTML code needed for our little application (`index.html`).

Added some whitespaceArmin Ronacherbefore adoption2912ff6

lines 124–167why, one step back
124Notice that we also drop the script directly into the HTML here. It is
125usually 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.