Skip to content

Instantly share code, notes, and snippets.

@aminnairi
Created January 25, 2022 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aminnairi/81e57a16b00e107ab0bb04f9b674af66 to your computer and use it in GitHub Desktop.
Save aminnairi/81e57a16b00e107ab0bb04f9b674af66 to your computer and use it in GitHub Desktop.
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