Seconde partie de l'exercice sur XMLHttpRequest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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