Created
January 25, 2022 10:39
-
-
Save aminnairi/81e57a16b00e107ab0bb04f9b674af66 to your computer and use it in GitHub Desktop.
Seconde partie de l'exercice sur XMLHttpRequest
This file contains hidden or 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