Skip to content
Myr

javascript.rst

This file

Path

docs/patterns/javascript.rst

259 lines · 8.8 KiB

Last changed by

Fix wrong spelling of JS method .innerHTMLnick2202before adoptionb7c1290

History of this file

Take it

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

Merge branch '2.1.x'David Lordbefore adoptiondcd1a1e

lines 1–30why, 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 use

Merge branch '2.2.x'David Lordbefore adoption73b9bac

line 31why, one step back
31JavaScript to affect how the Jinja template is rendered, but it is

Merge branch '2.1.x'David Lordbefore adoptiondcd1a1e

lines 32–127why, one step back
32possible 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.1.x'David Lordbefore adoptiondcd1a1e

lines 130–186why, 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 be139sent as well, otherwise Flask will return a 400 error.140141.. code-block:: javascript142143 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(...)152153.. |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/FormData157158159Following Redirects160-------------------161162A response might be a redirect, for example if you logged in with163JavaScript instead of a traditional HTML form, and your view returned164a redirect instead of JSON. JavaScript requests do follow redirects, but165they don't change the page. If you want to make the page change you can166inspect the response and apply the redirect manually.167168.. code-block:: javascript169170 fetch("/login", {"body": ...}).then(171 response => {172 if (response.redirected) {173 window.location = response.url174 } else {175 showLoginError()176 }177 }178 )179180181Replacing Content182-----------------183184A response might be new HTML, either a new section of the page to add or185replace, or an entirely new page. In general, if you're returning the186entire page, it would be better to handle that with a redirect as shown

Merge remote-tracking branch 'origin/2.1.x'David Lordbefore adoption96d39c8

lines 187–188why, one step back
187in the previous section. The following example shows how to replace a
188``<div>`` with the HTML returned by a request.

Merge branch '2.1.x'David Lordbefore adoptiondcd1a1e

lines 189–199why, one step back
189
190.. code-block:: html191192 <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)

Fix wrong spelling of JS method .innerHTMLnick2202before adoptionb7c1290

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

Merge branch '2.1.x'David Lordbefore adoptiondcd1a1e

lines 201–259why, one step back
201 </script>
202203204Return JSON from Views205----------------------206207To return a JSON object from your API view, you can directly return a208dict from the view. It will be serialized to JSON automatically.209210.. code-block:: python211212 @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 }220221If you want to return another JSON type, use the222:func:`~flask.json.jsonify` function, which creates a response object223with the given data serialized to JSON.224225.. code-block:: python226227 from flask import jsonify228229 @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])233234It is usually not a good idea to return file data in a JSON response.235JSON cannot represent binary data directly, so it must be base64236encoded, which can be slow, takes more bandwidth to send, and is not as237easy to cache. Instead, serve files using one view, and generate a URL238to the desired file to include in the JSON. Then the client can make a239separate request to get the linked resource after getting the JSON.240241242Receiving JSON in Views243-----------------------244245Use the :attr:`~flask.Request.json` property of the246:data:`~flask.request` object to decode the request's body as JSON. If247the body is not valid JSON, or the ``Content-Type`` header is not set to248``application/json``, a 400 Bad Request error will be raised.249250.. code-block:: python251252 from flask import request253254 @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()