rewrite javascript docs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent 6f6e328 · Browse files · 3 files·+263 added−146 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+263 added−146 removed
- other:+263 added−146 removed
Provenance
- Commit
2f3c87d- Tree
32378ba- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
6f6e328
3 files changed+263 added−146 removed
modified:docs/patterns/index.rst+1 added-1 removed
27 unmodified lines28 viewdecorators29 wtforms30 templateinheritance31 flashing32- jquery32+ javascript33 lazyloading34 mongoengine35 favicon36 streaming6 unmodified linesadded:docs/patterns/javascript.rst+259 added
1+JavaScript, ``fetch``, and JSON2+===============================3+4+You may want to make your HTML page dynamic, by changing data without5+reloading the entire page. Instead of submitting an HTML ``<form>`` and6+performing a redirect to re-render the template, you can add7+`JavaScript`_ that calls |fetch|_ and replaces content on the page.8+9+|fetch|_ is the modern, built-in JavaScript solution to making10+requests from a page. You may have heard of other "AJAX" methods and11+libraries, such as |XHR|_ or `jQuery`_. These are no longer needed in12+modern browsers, although you may choose to use them or another library13+depending on your application's requirements. These docs will only focus14+on built-in JavaScript features.15+16+.. _JavaScript: https://developer.mozilla.org/Web/JavaScript17+.. |fetch| replace:: ``fetch()``18+.. _fetch: https://developer.mozilla.org/Web/API/Fetch_API19+.. |XHR| replace:: ``XMLHttpRequest()``20+.. _XHR: https://developer.mozilla.org/Web/API/XMLHttpRequest21+.. _jQuery: https://jquery.com/22+23+24+Rendering Templates25+-------------------26+27+It is important to understand the difference between templates and28+JavaScript. Templates are rendered on the server, before the response is29+sent to the user's browser. JavaScript runs in the user's browser, after30+the template is rendered and sent. Therefore, it is impossible to use31+JavaScript to affect how the Jinja template is rendered, but is is32+possible to render data into the JavaScript that will run.33+34+To provide data to JavaScript when rendering the template, use the35+:func:`~jinja-filters.tojson` filter in a ``<script>`` block. This will36+convert the data to a valid JavaScript object, and ensure that any37+unsafe HTML characters are rendered safely. If you do not use the38+``tojson`` filter, you will get a ``SyntaxError`` in the browser39+console.40+41+.. code-block:: python42+43+ data = generate_report()44+ return render_template("report.html", chart_data=data)45+46+.. code-block:: jinja47+48+ <script>49+ const chart_data = {{ chart_data|tojson }}50+ chartLib.makeChart(chart_data)51+ </script>52+53+A less common pattern is to add the data to a ``data-`` attribute on an54+HTML tag. In this case, you must use single quotes around the value, not55+double quotes, otherwise you will produce invalid or unsafe HTML.56+57+.. code-block:: jinja58+59+ <div data-chart='{{ chart_data|tojson }}'></div>60+61+62+Generating URLs63+---------------64+65+The other way to get data from the server to JavaScript is to make a66+request for it. First, you need to know the URL to request.67+68+The simplest way to generate URLs is to continue to use69+:func:`~flask.url_for` when rendering the template. For example:70+71+.. code-block:: javascript72+73+ const user_url = {{ url_for("user", id=current_user.id)|tojson }}74+ fetch(user_url).then(...)75+76+However, you might need to generate a URL based on information you only77+know in JavaScript. As discussed above, JavaScript runs in the user's78+browser, not as part of the template rendering, so you can't use79+``url_for`` at that point.80+81+In this case, you need to know the "root URL" under which your82+application is served. In simple setups, this is ``/``, but it might83+also be something else, like ``https://example.com/myapp/``.84+85+A simple way to tell your JavaScript code about this root is to set it86+as a global variable when rendering the template. Then you can use it87+when generating URLs from JavaScript.88+89+.. code-block:: javascript90+91+ const SCRIPT_ROOT = {{ request.script_root|tojson }}92+ let user_id = ... // do something to get a user id from the page93+ let user_url = `${SCRIPT_ROOT}/user/${user_id}`94+ fetch(user_url).then(...)95+96+97+Making a Request with ``fetch``98+-------------------------------99+100+|fetch|_ takes two arguments, a URL and an object with other options,101+and returns a |Promise|_. We won't cover all the available options, and102+will only use ``then()`` on the promise, not other callbacks or103+``await`` syntax. Read the linked MDN docs for more information about104+those features.105+106+By default, the GET method is used. If the response contains JSON, it107+can be used with a ``then()`` callback chain.108+109+.. code-block:: javascript110+111+ const room_url = {{ url_for("room_detail", id=room.id)|tojson }}112+ fetch(room_url)113+ .then(response => response.json())114+ .then(data => {115+ // data is a parsed JSON object116+ })117+118+To send data, use a data method such as POST, and pass the ``body``119+option. The most common types for data are form data or JSON data.120+121+To send form data, pass a populated |FormData|_ object. This uses the122+same format as an HTML form, and would be accessed with ``request.form``123+in a Flask view.124+125+.. code-block:: javascript126+127+ let data = new FormData()128+ data.append("name": "Flask Room")129+ data.append("description": "Talk about Flask here.")130+ fetch(room_url, {131+ "method": "POST",132+ "body": data,133+ }).then(...)134+135+In general, prefer sending request data as form data, as would be used136+when submitting an HTML form. JSON can represent more complex data, but137+unless you need that it's better to stick with the simpler format. When138+sending JSON data, the ``Content-Type: application/json`` header must be139+sent as well, otherwise Flask will return a 400 error.140+141+.. code-block:: javascript142+143+ let data = {144+ "name": "Flask Room",145+ "description": "Talk about Flask here.",146+ }147+ fetch(room_url, {148+ "method": "POST",149+ "headers": {"Content-Type": "application/json"},150+ "body": JSON.stringify(data),151+ }).then(...)152+153+.. |Promise| replace:: ``Promise``154+.. _Promise: https://developer.mozilla.org/Web/JavaScript/Reference/Global_Objects/Promise155+.. |FormData| replace:: ``FormData``156+.. _FormData: https://developer.mozilla.org/en-US/docs/Web/API/FormData157+158+159+Following Redirects160+-------------------161+162+A response might be a redirect, for example if you logged in with163+JavaScript instead of a traditional HTML form, and your view returned164+a redirect instead of JSON. JavaScript requests do follow redirects, but165+they don't change the page. If you want to make the page change you can166+inspect the response and apply the redirect manually.167+168+.. code-block:: javascript169+170+ fetch("/login", {"body": ...}).then(171+ response => {172+ if (response.redirected) {173+ window.location = response.url174+ } else {175+ showLoginError()176+ }177+ }178+ )179+180+181+Replacing Content182+-----------------183+184+A response might be new HTML, either a new section of the page to add or185+replace, or an entirely new page. In general, if you're returning the186+entire page, it would be better to handle that with a redirect as shown187+in the previous section. The following example shows how to a ``<div>``188+with the HTML returned by a request.189+190+.. code-block:: html191+192+ <div id="geology-fact">193+ {{ include "geology_fact.html" }}194+ </div>195+ <script>196+ const geology_url = {{ url_for("geology_fact")|tojson }}197+ const geology_div = getElementById("geology-fact")198+ fetch(geology_url)199+ .then(response => response.text)200+ .then(text => geology_div.innerHtml = text)201+ </script>202+203+204+Return JSON from Views205+----------------------206+207+To return a JSON object from your API view, you can directly return a208+dict from the view. It will be serialized to JSON automatically.209+210+.. code-block:: python211+212+ @app.route("/user/<int:id>")213+ def user_detail(id):214+ user = User.query.get_or_404(id)215+ return {216+ "username": User.username,217+ "email": User.email,218+ "picture": url_for("static", filename=f"users/{id}/profile.png"),219+ }220+221+If you want to return another JSON type, use the222+:func:`~flask.json.jsonify` function, which creates a response object223+with the given data serialized to JSON.224+225+.. code-block:: python226+227+ from flask import jsonify228+229+ @app.route("/users")230+ def user_list():231+ users = User.query.order_by(User.name).all()232+ return jsonify([u.to_json() for u in users])233+234+It is usually not a good idea to return file data in a JSON response.235+JSON cannot represent binary data directly, so it must be base64236+encoded, which can be slow, takes more bandwidth to send, and is not as237+easy to cache. Instead, serve files using one view, and generate a URL238+to the desired file to include in the JSON. Then the client can make a239+separate request to get the linked resource after getting the JSON.240+241+242+Receiving JSON in Views243+-----------------------244+245+Use the :attr:`~flask.Request.json` property of the246+:data:`~flask.request` object to decode the request's body as JSON. If247+the body is not valid JSON, or the ``Content-Type`` header is not set to248+``application/json``, a 400 Bad Request error will be raised.249+250+.. code-block:: python251+252+ from flask import request253+254+ @app.post("/user/<int:id>")255+ def user_update(id):256+ user = User.query.get_or_404(id)257+ user.update_from_json(request.json)258+ db.session.commit()259+ return user.to_json()modified:docs/patterns/jquery.rst+3 added-145 removed
1+:orphan:2+3 AJAX with jQuery4 ================5 4-`jQuery`_ is a small JavaScript library commonly used to simplify working5-with the DOM and JavaScript in general. It is the perfect tool to make6-web applications more dynamic by exchanging JSON between server and7-client.8-9-JSON itself is a very lightweight transport format, very similar to how10-Python primitives (numbers, strings, dicts and lists) look like which is11-widely supported and very easy to parse. It became popular a few years12-ago and quickly replaced XML as transport format in web applications.13-14-.. _jQuery: https://jquery.com/15-16-Loading jQuery17---------------18-19-In order to use jQuery, you have to download it first and place it in the20-static folder of your application and then ensure it's loaded. Ideally21-you have a layout template that is used for all pages where you just have22-to add a script statement to the bottom of your ``<body>`` to load jQuery:23-24-.. sourcecode:: html25-26- <script src="{{ url_for('static', filename='jquery.js') }}"></script>27-28-Another method is using Google's `AJAX Libraries API29-<https://developers.google.com/speed/libraries/>`_ to load jQuery:30-31-.. sourcecode:: html32-33- <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>36-37-In this case you have to put jQuery into your static folder as a fallback, but it will38-first try to load it directly from Google. This has the advantage that your39-website will probably load faster for users if they went to at least one40-other website before using the same jQuery version from Google because it41-will already be in the browser cache.42-43-Where is My Site?44------------------45-46-Do you know where your application is? If you are developing the answer47-is quite simple: it's on localhost port something and directly on the root48-of that server. But what if you later decide to move your application to49-a different location? For example to ``http://example.com/myapp``? On50-the server side this never was a problem because we were using the handy51-:func:`~flask.url_for` function that could answer that question for52-us, but if we are using jQuery we should not hardcode the path to53-the application but make that dynamic, so how can we do that?54-55-A simple method would be to add a script tag to our page that sets a56-global variable to the prefix to the root of the application. Something57-like this:58-59-.. sourcecode:: html+jinja60-61- <script>62- $SCRIPT_ROOT = {{ request.script_root|tojson }};63- </script>64-65-66-JSON View Functions67--------------------68-69-Now let's create a server side function that accepts two URL arguments of70-numbers which should be added together and then sent back to the71-application in a JSON object. This is a really ridiculous example and is72-something you usually would do on the client side alone, but a simple73-example that shows how you would use jQuery and Flask nonetheless::74-75- from flask import Flask, jsonify, render_template, request76- app = Flask(__name__)77-78- @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)83-84- @app.route('/')85- def index():86- return render_template('index.html')87-88-As you can see I also added an `index` method here that renders a89-template. This template will load jQuery as above and have a little form where90-we can add two numbers and a link to trigger the function on the server91-side.92-93-Note that we are using the :meth:`~werkzeug.datastructures.MultiDict.get` method here94-which will never fail. If the key is missing a default value (here ``0``)95-is returned. Furthermore it can convert values to a specific type (like96-in our case `int`). This is especially handy for code that is97-triggered by a script (APIs, JavaScript etc.) because you don't need98-special error reporting in that case.99-100-The HTML101---------102-103-Your index.html template either has to extend a :file:`layout.html` template with104-jQuery loaded and the `$SCRIPT_ROOT` variable set, or do that on the top.105-Here's the HTML code needed for our little application (:file:`index.html`).106-Notice that we also drop the script directly into the HTML here. It is107-usually a better idea to have that in a separate script file:108-109-.. sourcecode:: html110-111- <script>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>129-130-I won't go into detail here about how jQuery works, just a very quick131-explanation of the little bit of code above:132-133-1. ``$(function() { ... })`` specifies code that should run once the134- browser is done loading the basic parts of the page.135-2. ``$('selector')`` selects an element and lets you operate on it.136-3. ``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).140-4. ``$.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.145-146-Check out the :gh:`example source <examples/javascript>` for a full147-application demonstrating the code on this page, as well as the same148-thing using ``XMLHttpRequest`` and ``fetch``.6+Obsolete, see :doc:`/patterns/javascript` instead.