jquery.rst
This file
Path
docs/patterns/jquery.rst
149 lines · 5.9 KiB
Last changed by
Merge pull request #3895 from pallets/jinja-tojsonDavid Lordbefore adoption192f4ae
History of this fileTake it
The walk stopped after 200 commits: lines older than 5ceb0a5 point at it.
Merge branch '1.1.x'Armin Ronacherbefore adoption5ceb0a5
lines 1–62why, one step back1AJAX with jQuery2================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:: 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/>`_ 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>Merge pull request #3895 from pallets/jinja-tojsonDavid Lordbefore adoption192f4ae
line 63why, one step back63 $SCRIPT_ROOT = {{ request.script_root|tojson }};Merge branch '1.1.x'Armin Ronacherbefore adoption5ceb0a5
lines 64–149why, one step back64 </script>656667JSON View Functions68-------------------6970Now let's create a server side function that accepts two URL arguments of71numbers which should be added together and then sent back to the72application in a JSON object. This is a really ridiculous example and is73something you usually would do on the client side alone, but a simple74example that shows how you would use jQuery and Flask nonetheless::7576 from flask import Flask, jsonify, render_template, request77 app = Flask(__name__)7879 @app.route('/_add_numbers')80 def add_numbers():81 a = request.args.get('a', 0, type=int)82 b = request.args.get('b', 0, type=int)83 return jsonify(result=a + b)8485 @app.route('/')86 def index():87 return render_template('index.html')8889As you can see I also added an `index` method here that renders a90template. This template will load jQuery as above and have a little form where91we can add two numbers and a link to trigger the function on the server92side.9394Note that we are using the :meth:`~werkzeug.datastructures.MultiDict.get` method here95which will never fail. If the key is missing a default value (here ``0``)96is returned. Furthermore it can convert values to a specific type (like97in our case `int`). This is especially handy for code that is98triggered by a script (APIs, JavaScript etc.) because you don't need99special error reporting in that case.100101The HTML102--------103104Your index.html template either has to extend a :file:`layout.html` template with105jQuery loaded and the `$SCRIPT_ROOT` variable set, or do that on the top.106Here's the HTML code needed for our little application (:file:`index.html`).107Notice that we also drop the script directly into the HTML here. It is108usually a better idea to have that in a separate script file:109110.. sourcecode:: html111112 <script type=text/javascript>113 $(function() {114 $('a#calculate').bind('click', function() {115 $.getJSON($SCRIPT_ROOT + '/_add_numbers', {116 a: $('input[name="a"]').val(),117 b: $('input[name="b"]').val()118 }, function(data) {119 $("#result").text(data.result);120 });121 return false;122 });123 });124 </script>125 <h1>jQuery Example</h1>126 <p><input type=text size=5 name=a> +127 <input type=text size=5 name=b> =128 <span id=result>?</span>129 <p><a href=# id=calculate>calculate server side</a>130131I won't go into detail here about how jQuery works, just a very quick132explanation of the little bit of code above:1331341. ``$(function() { ... })`` specifies code that should run once the135 browser is done loading the basic parts of the page.1362. ``$('selector')`` selects an element and lets you operate on it.1373. ``element.bind('event', func)`` specifies a function that should run138 when the user clicked on the element. If that function returns139 `false`, the default behavior will not kick in (in this case, navigate140 to the `#` URL).1414. ``$.getJSON(url, data, func)`` sends a ``GET`` request to `url` and will142 send the contents of the `data` object as query parameters. Once the143 data arrived, it will call the given function with the return value as144 argument. Note that we can use the `$SCRIPT_ROOT` variable here that145 we set earlier.146147Check out the :gh:`example source <examples/javascript>` for a full148application demonstrating the code on this page, as well as the same149thing using ``XMLHttpRequest`` and ``fetch``.