Veronika Milovzorova portfolio/ est

Harjutus 6. API päring

H6. API päring

  • Ava veebilehitsejas Code Sandbox sait
  • Vali Official Templates alt static
    Kirjuta pildil olev kood index.html faili. Alustuseks kasuta HTML trafaretti (hüüumärk ja tab klahv).
  • Salvesta fail CTRL + S
  • Lõpptulemuseks peaksid saama andmeid peekoni kohta
<!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>
    <style>
      .button-container {
        display: flex;
        justify-content: left;
        gap: 10px;
      }
    </style>
  </head>
  <body>
    <h1>6. API request bacon</h1>

    <div class="button-container">
      <button type="button" onclick="loadBacon()">Request bacon</button>
      <button type="button" onclick="loadBreakfast()">Request facts</button>
    </div>

    <p id="bacon-demo"></p>
    <p id="breakfast-demo"></p>

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

Kokkuvõte

xhttp.open(“GET, url”) – avab uus HTTP päring
xttp.send() – saadame päringu serverisse
XMLHttpRequest – AJAX päring mis saadab API aadressile päringu

et