Skip to content
Myr

javascript.rst

This file

Path

docs/patterns/javascript.rst

261 lines · 8.8 KiB

Last changed by

Merge branch 'stable'David Lordbefore adoption5880bef

History of this file

Take it

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

Merge branch '2.2.x'David Lordbefore adoptionef85270

lines 1–127why, one step back
1JavaScript, ``fetch``, and JSON
2===============================34You may want to make your HTML page dynamic, by changing data without5reloading the entire page. Instead of submitting an HTML ``<form>`` and6performing a redirect to re-render the template, you can add7`JavaScript`_ that calls |fetch|_ and replaces content on the page.89|fetch|_ is the modern, built-in JavaScript solution to making10requests from a page. You may have heard of other "AJAX" methods and11libraries, such as |XHR|_ or `jQuery`_. These are no longer needed in12modern browsers, although you may choose to use them or another library13depending on your application's requirements. These docs will only focus14on built-in JavaScript features.1516.. _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/222324Rendering Templates25-------------------2627It is important to understand the difference between templates and28JavaScript. Templates are rendered on the server, before the response is29sent to the user's browser. JavaScript runs in the user's browser, after30the template is rendered and sent. Therefore, it is impossible to use31JavaScript to affect how the Jinja template is rendered, but it is32possible to render data into the JavaScript that will run.3334To provide data to JavaScript when rendering the template, use the35:func:`~jinja-filters.tojson` filter in a ``<script>`` block. This will36convert the data to a valid JavaScript object, and ensure that any37unsafe HTML characters are rendered safely. If you do not use the38``tojson`` filter, you will get a ``SyntaxError`` in the browser39console.4041.. code-block:: python4243 data = generate_report()44 return render_template("report.html", chart_data=data)4546.. code-block:: jinja4748 <script>49 const chart_data = {{ chart_data|tojson }}50 chartLib.makeChart(chart_data)51 </script>5253A less common pattern is to add the data to a ``data-`` attribute on an54HTML tag. In this case, you must use single quotes around the value, not55double quotes, otherwise you will produce invalid or unsafe HTML.5657.. code-block:: jinja5859 <div data-chart='{{ chart_data|tojson }}'></div>606162Generating URLs63---------------6465The other way to get data from the server to JavaScript is to make a66request for it. First, you need to know the URL to request.6768The simplest way to generate URLs is to continue to use69:func:`~flask.url_for` when rendering the template. For example:7071.. code-block:: javascript7273 const user_url = {{ url_for("user", id=current_user.id)|tojson }}74 fetch(user_url).then(...)7576However, you might need to generate a URL based on information you only77know in JavaScript. As discussed above, JavaScript runs in the user's78browser, not as part of the template rendering, so you can't use79``url_for`` at that point.8081In this case, you need to know the "root URL" under which your82application is served. In simple setups, this is ``/``, but it might83also be something else, like ``https://example.com/myapp/``.8485A simple way to tell your JavaScript code about this root is to set it86as a global variable when rendering the template. Then you can use it87when generating URLs from JavaScript.8889.. code-block:: javascript9091 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(...)959697Making a Request with ``fetch``98-------------------------------99100|fetch|_ takes two arguments, a URL and an object with other options,101and returns a |Promise|_. We won't cover all the available options, and102will only use ``then()`` on the promise, not other callbacks or103``await`` syntax. Read the linked MDN docs for more information about104those features.105106By default, the GET method is used. If the response contains JSON, it107can be used with a ``then()`` callback chain.108109.. code-block:: javascript110111 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 })117118To send data, use a data method such as POST, and pass the ``body``119option. The most common types for data are form data or JSON data.120121To send form data, pass a populated |FormData|_ object. This uses the122same format as an HTML form, and would be accessed with ``request.form``123in a Flask view.124125.. code-block:: javascript126127 let data = new FormData()

Merge branch '2.3.x'David Lordbefore adoption31fd9c8

lines 128–129why, one step back
128 data.append("name", "Flask Room")
129 data.append("description", "Talk about Flask here.")

Merge branch '2.2.x'David Lordbefore adoptionef85270

lines 130–138why, one step back
130 fetch(room_url, {
131 "method": "POST",132 "body": data,133 }).then(...)134135In general, prefer sending request data as form data, as would be used136when submitting an HTML form. JSON can represent more complex data, but137unless you need that it's better to stick with the simpler format. When138sending JSON data, the ``Content-Type: application/json`` header must be

Merge branch 'stable'David Lordbefore adoption5880bef

lines 139–140why, one step back
139sent as well, otherwise Flask will return a 415 Unsupported Media Type
140error.

Merge branch '2.2.x'David Lordbefore adoptionef85270

lines 141–200why, one step back
141
142.. code-block:: javascript143144 let data = {145 "name": "Flask Room",146 "description": "Talk about Flask here.",147 }148 fetch(room_url, {149 "method": "POST",150 "headers": {"Content-Type": "application/json"},151 "body": JSON.stringify(data),152 }).then(...)153154.. |Promise| replace:: ``Promise``155.. _Promise: https://developer.mozilla.org/Web/JavaScript/Reference/Global_Objects/Promise156.. |FormData| replace:: ``FormData``157.. _FormData: https://developer.mozilla.org/en-US/docs/Web/API/FormData158159160Following Redirects161-------------------162163A response might be a redirect, for example if you logged in with164JavaScript instead of a traditional HTML form, and your view returned165a redirect instead of JSON. JavaScript requests do follow redirects, but166they don't change the page. If you want to make the page change you can167inspect the response and apply the redirect manually.168169.. code-block:: javascript170171 fetch("/login", {"body": ...}).then(172 response => {173 if (response.redirected) {174 window.location = response.url175 } else {176 showLoginError()177 }178 }179 )180181182Replacing Content183-----------------184185A response might be new HTML, either a new section of the page to add or186replace, or an entirely new page. In general, if you're returning the187entire page, it would be better to handle that with a redirect as shown188in the previous section. The following example shows how to replace a189``<div>`` with the HTML returned by a request.190191.. code-block:: html192193 <div id="geology-fact">194 {{ include "geology_fact.html" }}195 </div>196 <script>197 const geology_url = {{ url_for("geology_fact")|tojson }}198 const geology_div = getElementById("geology-fact")199 fetch(geology_url)200 .then(response => response.text)

Fix wrong spelling of JS method .innerHTMLnick2202before adoptionb7c1290

line 201why, one step back
201 .then(text => geology_div.innerHTML = text)

Merge branch '2.2.x'David Lordbefore adoptionef85270

lines 202–247why, one step back
202 </script>
203204205Return JSON from Views206----------------------207208To return a JSON object from your API view, you can directly return a209dict from the view. It will be serialized to JSON automatically.210211.. code-block:: python212213 @app.route("/user/<int:id>")214 def user_detail(id):215 user = User.query.get_or_404(id)216 return {217 "username": User.username,218 "email": User.email,219 "picture": url_for("static", filename=f"users/{id}/profile.png"),220 }221222If you want to return another JSON type, use the223:func:`~flask.json.jsonify` function, which creates a response object224with the given data serialized to JSON.225226.. code-block:: python227228 from flask import jsonify229230 @app.route("/users")231 def user_list():232 users = User.query.order_by(User.name).all()233 return jsonify([u.to_json() for u in users])234235It is usually not a good idea to return file data in a JSON response.236JSON cannot represent binary data directly, so it must be base64237encoded, which can be slow, takes more bandwidth to send, and is not as238easy to cache. Instead, serve files using one view, and generate a URL239to the desired file to include in the JSON. Then the client can make a240separate request to get the linked resource after getting the JSON.241242243Receiving JSON in Views244-----------------------245246Use the :attr:`~flask.Request.json` property of the247:data:`~flask.request` object to decode the request's body as JSON. If

Merge branch 'stable'David Lordbefore adoption5880bef

lines 248–250why, one step back
248the body is not valid JSON, a 400 Bad Request error will be raised. If
249the ``Content-Type`` header is not set to ``application/json``, a 415250Unsupported Media Type error will be raised.

Merge branch '2.2.x'David Lordbefore adoptionef85270

lines 251–261why, one step back
251
252.. code-block:: python253254 from flask import request255256 @app.post("/user/<int:id>")257 def user_update(id):258 user = User.query.get_or_404(id)259 user.update_from_json(request.json)260 db.session.commit()261 return user.to_json()