Skip to content

Instantly share code, notes, and snippets.

@aminnairi
Created Jan 25, 2022
Embed
What would you like to do?
Seconde partie de l'exercice sur XMLHttpRequest
const request = new XMLHttpRequest();
const errorElement = document.getElementById("error");
const postsElement = document.getElementById("posts");
request.addEventListener("timeout", function() {
errorElement.innerText = "Le délai d'attente maximum est dépassé pour la requête.";
});
request.addEventListener("error", function() {
errorElement.innerText = this.statusText;
});
request.addEventListener("load", function() {
try {
const posts = JSON.parse(this.responseText);
posts.forEach(function(post) {
const postRowElement = document.createElement("tr");
const postIdentifierCellElement = document.createElement("td");
const postUserCellElement = document.createElement("td");
const postTitleCellElement = document.createElement("td");
const postBodyCellElement = document.createElement("td");
postIdentifierCellElement.innerText = post.id;
postUserCellElement.innerText = `#${post.userId}`; // <a href="./user.html?identifier=${post.userId}">...</a>
postTitleCellElement.innerText = post.title
postBodyCellElement.innerText = post.body;
postRowElement.appendChild(postIdentifierCellElement);
postRowElement.appendChild(postUserCellElement);
postRowElement.appendChild(postTitleCellElement);
postRowElement.appendChild(postBodyCellElement);
postsElement.appendChild(postRowElement);
});
} catch (error) {
errorElement.innerText = error.message;
}
});
request.open("GET", "https://jsonplaceholder.typicode.com/posts");
request.send();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment