Skip to content
Myr

jquery.rst

This file

Path

docs/patterns/jquery.rst

148 lines · 5.8 KiB

Last changed by

Merge remote-tracking branch 'origin/2.0.x'David Lordbefore adoptionafc13b9

History of this file

Take it

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

Merge pull request #3667 from pallets/dependabot/pip/tox-3.16.0dependabot-preview[bot]before adoptionfe992ca

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.1314.. _jQuery: https://jquery.com/1516Loading 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:: html25

Merge remote-tracking branch 'origin/2.0.x'David Lordbefore adoptionafc13b9

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

Merge pull request #3667 from pallets/dependabot/pip/tox-3.16.0dependabot-preview[bot]before adoptionfe992ca

lines 27–60why, one step back
27
28Another method is using Google's `AJAX Libraries API29<https://developers.google.com/speed/libraries/>`_ to load jQuery:3031.. sourcecode:: html3233 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>34 <script>window.jQuery || document.write('<script src="{{35 url_for('static', filename='jquery.js') }}">\x3C/script>')</script>3637In this case you have to put jQuery into your static folder as a fallback, but it will38first try to load it directly from Google. This has the advantage that your39website will probably load faster for users if they went to at least one40other website before using the same jQuery version from Google because it41will already be in the browser cache.4243Where is My Site?44-----------------4546Do you know where your application is? If you are developing the answer47is quite simple: it's on localhost port something and directly on the root48of that server. But what if you later decide to move your application to49a different location? For example to ``http://example.com/myapp``? On50the server side this never was a problem because we were using the handy51:func:`~flask.url_for` function that could answer that question for52us, but if we are using jQuery we should not hardcode the path to53the application but make that dynamic, so how can we do that?5455A simple method would be to add a script tag to our page that sets a56global variable to the prefix to the root of the application. Something57like this:5859.. sourcecode:: html+jinja60

Merge remote-tracking branch 'origin/2.0.x'David Lordbefore adoptionafc13b9

line 61why, one step back
61 <script>

Merge pull request #3895 from pallets/jinja-tojsonDavid Lordbefore adoption192f4ae

line 62why, one step back
62 $SCRIPT_ROOT = {{ request.script_root|tojson }};

Merge pull request #3667 from pallets/dependabot/pip/tox-3.16.0dependabot-preview[bot]before adoptionfe992ca

lines 63–110why, one step back
63 </script>
646566JSON View Functions67-------------------6869Now let's create a server side function that accepts two URL arguments of70numbers which should be added together and then sent back to the71application in a JSON object. This is a really ridiculous example and is72something you usually would do on the client side alone, but a simple73example that shows how you would use jQuery and Flask nonetheless::7475 from flask import Flask, jsonify, render_template, request76 app = Flask(__name__)7778 @app.route('/_add_numbers')79 def add_numbers():80 a = request.args.get('a', 0, type=int)81 b = request.args.get('b', 0, type=int)82 return jsonify(result=a + b)8384 @app.route('/')85 def index():86 return render_template('index.html')8788As you can see I also added an `index` method here that renders a89template. This template will load jQuery as above and have a little form where90we can add two numbers and a link to trigger the function on the server91side.9293Note that we are using the :meth:`~werkzeug.datastructures.MultiDict.get` method here94which will never fail. If the key is missing a default value (here ``0``)95is returned. Furthermore it can convert values to a specific type (like96in our case `int`). This is especially handy for code that is97triggered by a script (APIs, JavaScript etc.) because you don't need98special error reporting in that case.99100The HTML101--------102103Your index.html template either has to extend a :file:`layout.html` template with104jQuery loaded and the `$SCRIPT_ROOT` variable set, or do that on the top.105Here's the HTML code needed for our little application (:file:`index.html`).106Notice that we also drop the script directly into the HTML here. It is107usually a better idea to have that in a separate script file:108109.. sourcecode:: html110

Merge remote-tracking branch 'origin/2.0.x'David Lordbefore adoptionafc13b9

line 111why, one step back
111 <script>

Merge pull request #3667 from pallets/dependabot/pip/tox-3.16.0dependabot-preview[bot]before adoptionfe992ca

lines 112–148why, one step back
112 $(function() {
113 $('a#calculate').bind('click', function() {114 $.getJSON($SCRIPT_ROOT + '/_add_numbers', {115 a: $('input[name="a"]').val(),116 b: $('input[name="b"]').val()117 }, function(data) {118 $("#result").text(data.result);119 });120 return false;121 });122 });123 </script>124 <h1>jQuery Example</h1>125 <p><input type=text size=5 name=a> +126 <input type=text size=5 name=b> =127 <span id=result>?</span>128 <p><a href=# id=calculate>calculate server side</a>129130I won't go into detail here about how jQuery works, just a very quick131explanation of the little bit of code above:1321331. ``$(function() { ... })`` specifies code that should run once the134 browser is done loading the basic parts of the page.1352. ``$('selector')`` selects an element and lets you operate on it.1363. ``element.bind('event', func)`` specifies a function that should run137 when the user clicked on the element. If that function returns138 `false`, the default behavior will not kick in (in this case, navigate139 to the `#` URL).1404. ``$.getJSON(url, data, func)`` sends a ``GET`` request to `url` and will141 send the contents of the `data` object as query parameters. Once the142 data arrived, it will call the given function with the return value as143 argument. Note that we can use the `$SCRIPT_ROOT` variable here that144 we set earlier.145146Check out the :gh:`example source <examples/javascript>` for a full147application demonstrating the code on this page, as well as the same148thing using ``XMLHttpRequest`` and ``fetch``.