jquery.rst
This file
Path
docs/patterns/jquery.rst
167 lines · 6.6 KiB
Last changed by
Fix typos and remove unused import.florentxbefore adoption3c821a0
History of this fileTake it
With -> with in headlineArmin Ronacherbefore adoptionf878919
line 1why, one step back1AJAX with jQueryAdded JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a
lines 2–8why, one step back2================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.8Finished jQuery example documentation.Armin Ronacherbefore adoptiona99e408
lines 9–16why, one step back9JSON 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.16Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a
line 17why, one step back17.. _jQuery: http://jquery.com/Finished jQuery example documentation.Armin Ronacherbefore adoptiona99e408
line 18why, one step back18.. _simplejson: http://pypi.python.org/pypi/simplejsonAdded JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a
lines 19–25why, one step back1920Loading 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 haveFinished jQuery example documentation.Armin Ronacherbefore adoptiona99e408
line 26why, one step back26to 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 back2728.. sourcecode:: html2930 <script type=text/javascript src="{{Finished jQuery example documentation.Armin Ronacherbefore adoptiona99e408
line 31why, one step back31 url_for('static', filename='jquery.js') }}"></script>Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a
line 32why, one step back32Finished jQuery example documentation.Armin Ronacherbefore adoptiona99e408
lines 33–47why, one step back33Another 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.47Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a
lines 48–79why, one step back48Where 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 andFixed a security problem caused by changed simplejson semantics.Armin Ronacherbefore adoptionade4905
lines 80–81why, one step back80 escape slashes for you (``{{ "</script>"|tojson|safe }`` is rendered as81 ``"<\/script>"``).Finished jQuery example documentation.Armin Ronacherbefore adoptiona99e408
lines 82–90why, one step back828384JSON 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 simpleSome more documentation updates.Armin Ronacherbefore adoption715f64d
line 91why, one step back91example that shows how you would use jQuery and Flask nonetheless::Finished jQuery example documentation.Armin Ronacherbefore adoptiona99e408
lines 92–109why, one step back9293 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.Some more documentation updates.Armin Ronacherbefore adoption715f64d
lines 110–113why, one step back110111Note that we are using the :meth:`~werkzeug.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 (likeFix typos and remove unused import.florentxbefore adoption3c821a0
line 114why, one step back114in our case `int`). This is especially handy for code that isSome more documentation updates.Armin Ronacherbefore adoption715f64d
lines 115–116why, one step back115triggered by a script (APIs, JavaScript etc.) because you don't need116special error reporting in that case.Finished jQuery example documentation.Armin Ronacherbefore adoptiona99e408
lines 117–167why, one step back117118The HTML119--------120121You 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 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.