H:6 päring API

Avasin CodeSandbox ja avasin HTML + CSS projekti

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Static Template</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <button type="button" onclick="loadDoc()">Request bacon</button>
    <p id="demo"></p>

    <script>
      function loadDoc() {
        const xhttp = new XMLHttpRequest();
        xhttp.onload = function () {
          document.getElementById("demo").innerHTML = this.responseText;
        };
        xhttp.open("GET", "https://baconipsum.com/api/?type=all-meat");
        xhttp.send();
      }
    </script>
  </body>
</html>

Lisasin veel 2 nuppu

function loadDoc2() {
        const xhttp = new XMLHttpRequest();
        xhttp.onload = function () {
          document.getElementById("demo2").innerHTML = this.responseText;
        };
        xhttp.open("GET", "https://catfact.ninja/fact");
        xhttp.send();
      }

      function loadDoc3() {
        const xhttp = new XMLHttpRequest();
        xhttp.onload = function () {
          document.getElementById("demo3").innerHTML = this.responseText;
        };
        xhttp.open(
          "GET",
          "https://www.themealdb.com/api/json/v1/1/filter.php?c=Breakfast"
        );
        xhttp.send();
      }

ja CSS

h1 {
  text-decoration: underline;
}

body {
  font-family: Arial, sans-serif;
  background-color: #f9f9f9;
  padding: 30px;
  text-align: center;
  color: #333;
}

button {
  background-color: #ff6347;
  border: none;
  color: white;
  padding: 12px 25px;
  font-size: 16px;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #e5533d;
}

#demo,
#demo2,
#demo3 {
  margin-top: 20px;
  font-size: 18px;
  line-height: 1.5;
  max-width: 600px;
  margin-left: auto;
  margin-right: auto;
  background-color: #fff;
  padding: 15px 20px;
  border-radius: 5px;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
  white-space: pre-wrap;
}

Kokkuvõtte

xhttp.open(“GET”, url) – avab uus HTTP päring

xttp.send() – saadab päringu serverisse

XMLHTttpRequest – AJAX päring mis saadab API aadressile päringu