A Page That Calls the API
Part of the JSON APIs section of Coddy's Django journey. Lesson 12 of 19.
Your own site can call the API too, from JavaScript on the home page. The page loads once, then its script asks the API for data and fills the page without a reload. The starter's home page no longer draws the list itself; the script will. The script, tasks/static/tasks/app.js, is given; your part is the page it needs.
fetch("/api/tasks/") sends a GET from the visitor's browser, and response.json() reads the response. document.getElementById("task-list") finds the element whose id is task-list, so the page must have one. A script runs as soon as the browser reads its tag, so the tag goes after the elements it uses, at the end of the body. Load it through {% static %}:
{% load static %}
<script src="{% static 'shop/cart.js' %}"></script>The checks cannot run JavaScript, so they test the page and the JSON; the preview runs the script for real.
Challenge
MediumRead tasks/static/tasks/app.js, then in tasks/templates/tasks/home.html add the list the script fills, with the id it looks up. Load tasks/app.js through {% static %}, placed so the list exists when the script runs.
Press Run: Buy milk, Write the report and Call the bank appear on the home page.
Try it yourself
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Task tracker</title>
</head>
<body>
<h1>Task tracker</h1>
</body>
</html>
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in JSON APIs
Practice on your own: Django playground