H6.API päring

index.html

<!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>
    <h1>API Requests</h1>
    <button type="button" onclick="loadCatFact()">Request Cat Fact</button>
    <button type="button" onclick="loaDoc()">Request Bacon</button>
    <p id="demo"></p>

    <script>
      function loaDoc() {
        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();
      }
      function loadCatFact() {
        const xhttp = new XMLHttpRequest();
        xhttp.onload = function () {
          document.getElementById("demo").innerHTML = this.responseText;
        };
        xhttp.open("GET", "https://catfact.ninja/fact");
        xhttp.send();
      }
    </script>
  </body>
</html>

style.css

<!-- wp:code -->
<pre class="wp-block-code"><code>/* General body styles */
body {
  font-family: Arial, sans-serif;
  background-color: #f7f7f7;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  text-align: center;
}

/* Header styles */
h1 {
  color: #2d3e50;
  font-size: 2.5rem;
  margin-bottom: 20px;
  font-weight: 600;
}

/* Button styles */
button {
  background-color: #2b0474;
  color: white;
  border: none;
  padding: 15px 25px;
  font-size: 1rem;
  cursor: pointer;
  border-radius: 5px;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #0a0dee;
}

/* Paragraph styles */
p {
  font-size: 1.25rem;
  color: #333;
  margin-top: 20px;
  max-width: 800px;
  line-height: 1.5;
  word-wrap: break-word;
}
</code></pre>
<!-- /wp:code -->

Kokkuvõte

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

xhttp.send() – saadab päring serverisse

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