Working With Api
working-with-api.html
working-with-api.html
<!DOCTYPE html>
<html>
<head>
<title>XHR vs Fetch</title>
</head>
<body>
<h1>Working with APIs</h1>
<button id="xhrBtn">Load with XHR</button>
<button id="fetchBtn">Load with Fetch</button>
<ul id="list"></ul>
<script>
const list = document.getElementById("list");
function renderUsers(users) {
list.innerHTML = "";
users.forEach(user => {
const li = document.createElement("li");
li.textContent = user.name;
list.appendChild(li);
});
}
// XMLHTTPREQUEST (OLD WAY)
document.getElementById("xhrBtn").addEventListener("click", () => {
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/users");
xhr.onload = function () {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log("XHR Users:", data);
renderUsers(data);
} else {
console.error("XHR Error:", xhr.status);
}
};
xhr.onerror = function () {
console.error("XHR Network Error");
};
xhr.send();
});
// FETCH (MODERN WAY)
document.getElementById("fetchBtn").addEventListener("click", async () => {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
if (!response.ok) throw new Error("Fetch error");
const data = await response.json();
console.log("Fetch Users:", data);
renderUsers(data);
} catch (err) {
console.error(err.message);
}
});
</script>
</body>
</html>
working-with-api.html
working-with-api.html
<!DOCTYPE html>
<html>
<head>
<title>XHR vs Fetch</title>
</head>
<body>
<h1>Working with APIs</h1>
<button id="xhrBtn">Load with XHR</button>
<button id="fetchBtn">Load with Fetch</button>
<ul id="list"></ul>
<script>
const list = document.getElementById("list");
function renderUsers(users) {
list.innerHTML = "";
users.forEach(user => {
const li = document.createElement("li");
li.textContent = user.name;
list.appendChild(li);
});
}
// XMLHTTPREQUEST (OLD WAY)
document.getElementById("xhrBtn").addEventListener("click", () => {
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/users");
xhr.onload = function () {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log("XHR Users:", data);
renderUsers(data);
} else {
console.error("XHR Error:", xhr.status);
}
};
xhr.onerror = function () {
console.error("XHR Network Error");
};
xhr.send();
});
// FETCH (MODERN WAY)
document.getElementById("fetchBtn").addEventListener("click", async () => {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
if (!response.ok) throw new Error("Fetch error");
const data = await response.json();
console.log("Fetch Users:", data);
renderUsers(data);
} catch (err) {
console.error(err.message);
}
});
</script>
</body>
</html>