Skip to content
Myr

jquery.rst

This file

Path

docs/patterns/jquery.rst

167 lines · 6.7 KiB

Last changed by

Merge branch '1.0-maintenance'David Lordbefore adoptionac6746d

History of this file

Take it

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

Merge pull request #2436 from davidism/loggingDavid Lordbefore adoptionc74f469

lines 1–13why, 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.13

Merge pull request #2969 from codeaditya/update-linksDavid Lordbefore adoption7e714bd

line 14why, one step back
14.. _jQuery: https://jquery.com/

Merge pull request #2436 from davidism/loggingDavid Lordbefore adoptionc74f469

lines 15–107why, one step back
15
16Loading jQuery17--------------1819In order to use jQuery, you have to download it first and place it in the20static folder of your application and then ensure it's loaded. Ideally21you have a layout template that is used for all pages where you just have22to add a script statement to the bottom of your ``<body>`` to load jQuery:2324.. sourcecode:: html2526 <script type=text/javascript src="{{27 url_for('static', filename='jquery.js') }}"></script>2829Another method is using Google's `AJAX Libraries API30<https://developers.google.com/speed/libraries/devguide>`_ to load jQuery:3132.. sourcecode:: html3334 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>35 <script>window.jQuery || document.write('<script src="{{36 url_for('static', filename='jquery.js') }}">\x3C/script>')</script>3738In this case you have to put jQuery into your static folder as a fallback, but it will39first try to load it directly from Google. This has the advantage that your40website will probably load faster for users if they went to at least one41other website before using the same jQuery version from Google because it42will already be in the browser cache.4344Where is My Site?45-----------------4647Do you know where your application is? If you are developing the answer48is quite simple: it's on localhost port something and directly on the root49of that server. But what if you later decide to move your application to50a different location? For example to ``http://example.com/myapp``? On51the server side this never was a problem because we were using the handy52:func:`~flask.url_for` function that could answer that question for53us, but if we are using jQuery we should not hardcode the path to54the application but make that dynamic, so how can we do that?5556A simple method would be to add a script tag to our page that sets a57global variable to the prefix to the root of the application. Something58like this:5960.. sourcecode:: html+jinja6162 <script type=text/javascript>63 $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};64 </script>6566The ``|safe`` is necessary in Flask before 0.10 so that Jinja does not67escape the JSON encoded string with HTML rules. Usually this would be68necessary, but we are inside a ``script`` block here where different rules69apply.7071.. admonition:: Information for Pros7273 In HTML the ``script`` tag is declared ``CDATA`` which means that entities74 will not be parsed. Everything until ``</script>`` is handled as script.75 This also means that there must never be any ``</`` between the script76 tags. ``|tojson`` is kind enough to do the right thing here and77 escape slashes for you (``{{ "</script>"|tojson|safe }}`` is rendered as78 ``"<\/script>"``).7980 In Flask 0.10 it goes a step further and escapes all HTML tags with81 unicode escapes. This makes it possible for Flask to automatically82 mark the result as HTML safe.838485JSON View Functions86-------------------8788Now let's create a server side function that accepts two URL arguments of89numbers which should be added together and then sent back to the90application in a JSON object. This is a really ridiculous example and is91something you usually would do on the client side alone, but a simple92example that shows how you would use jQuery and Flask nonetheless::9394 from flask import Flask, jsonify, render_template, request95 app = Flask(__name__)9697 @app.route('/_add_numbers')98 def add_numbers():99 a = request.args.get('a', 0, type=int)100 b = request.args.get('b', 0, type=int)101 return jsonify(result=a + b)102103 @app.route('/')104 def index():105 return render_template('index.html')106107As you can see I also added an `index` method here that renders a

Merge branch '1.0-maintenance'David Lordbefore adoptionac6746d

line 108why, one step back
108template. This template will load jQuery as above and have a little form where

Merge pull request #2436 from davidism/loggingDavid Lordbefore adoptionc74f469

lines 109–164why, one step back
109we can add two numbers and a link to trigger the function on the server
110side.111112Note that we are using the :meth:`~werkzeug.datastructures.MultiDict.get` method here113which will never fail. If the key is missing a default value (here ``0``)114is returned. Furthermore it can convert values to a specific type (like115in our case `int`). This is especially handy for code that is116triggered by a script (APIs, JavaScript etc.) because you don't need117special error reporting in that case.118119The HTML120--------121122Your index.html template either has to extend a :file:`layout.html` template with123jQuery loaded and the `$SCRIPT_ROOT` variable set, or do that on the top.124Here's the HTML code needed for our little application (:file:`index.html`).125Notice that we also drop the script directly into the HTML here. It is126usually a better idea to have that in a separate script file:127128.. sourcecode:: html129130 <script type=text/javascript>131 $(function() {132 $('a#calculate').bind('click', function() {133 $.getJSON($SCRIPT_ROOT + '/_add_numbers', {134 a: $('input[name="a"]').val(),135 b: $('input[name="b"]').val()136 }, function(data) {137 $("#result").text(data.result);138 });139 return false;140 });141 });142 </script>143 <h1>jQuery Example</h1>144 <p><input type=text size=5 name=a> +145 <input type=text size=5 name=b> =146 <span id=result>?</span>147 <p><a href=# id=calculate>calculate server side</a>148149I won't go into detail here about how jQuery works, just a very quick150explanation of the little bit of code above:1511521. ``$(function() { ... })`` specifies code that should run once the153 browser is done loading the basic parts of the page.1542. ``$('selector')`` selects an element and lets you operate on it.1553. ``element.bind('event', func)`` specifies a function that should run156 when the user clicked on the element. If that function returns157 `false`, the default behavior will not kick in (in this case, navigate158 to the `#` URL).1594. ``$.getJSON(url, data, func)`` sends a ``GET`` request to `url` and will160 send the contents of the `data` object as query parameters. Once the161 data arrived, it will call the given function with the return value as162 argument. Note that we can use the `$SCRIPT_ROOT` variable here that163 we set earlier.164

Merge pull request #2699 from pallets/javascriptDavid Lordbefore adoption746b91d

line 165why, one step back
165Check out the :gh:`example source <examples/javascript>` for a full

clean up js exampleDavid Lordbefore adoption1e84c67

line 166why, one step back
166application demonstrating the code on this page, as well as the same

Merge pull request #2699 from pallets/javascriptDavid Lordbefore adoption746b91d

line 167why, one step back
167thing using ``XMLHttpRequest`` and ``fetch``.