1.Loo uus HTML ja CSS keskkond CodeSandboxis
2.Kirjuta kood
<!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>Bacon Service</h1>
<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>
3. see kuvandab pekoonitoidud

4. Lisatud üks veel nupp ja css
<!DOCTYPE html>
<html>
<head>
<title>Static template</title>
<meta charset="UTF-8" />
<link rel="stylesheet" href="styles.css" />
<script>
document.addEventListener("DOMContentLoaded", function () {
const baconResult = document.getElementById("baconResult");
const catFactResult = document.getElementById("catFactResult");
function loadBacon() {
catFactResult.style.display = "none";
const xhttp = new XMLHttpRequest();
xhttp.onload = function () {
baconResult.innerHTML = this.responseText;
baconResult.style.display = "block";
};
xhttp.open("GET", "https://baconipsum.com/api/?type=all-meat");
xhttp.send();
}
function loadCatFact() {
baconResult.style.display = "none";
const xhttp = new XMLHttpRequest();
xhttp.onload = function () {
const data = JSON.parse(this.responseText);
catFactResult.innerHTML = data.fact;
catFactResult.style.display = "block";
};
xhttp.open("GET", "https://catfact.ninja/fact");
xhttp.send();
}
document
.getElementById("baconBtn")
.addEventListener("click", loadBacon);
document
.getElementById("catFactBtn")
.addEventListener("click", loadCatFact);
});
</script>
</head>
<body>
<section>
<h1>Bacon service</h1>
<button type="button" id="baconBtn">Request bacon</button>
<p id="baconResult"></p>
</section>
<section>
<h1>Cat fact service</h1>
<button type="button" id="catFactBtn">Request cat fact</button>
<p id="catFactResult"></p>
</section>
</body>
</html>

Kokkuvõte
xhttp.open(“GET”, “url”) – avab uus HTTP päring
xhhtp.send() – saadab päringu serverisse
XMLHTTPrequest – AJAX päring mis saadab API aadressile päringu