Apprendre à charger et afficher des données depuis un fichier JSON local en utilisant l'API fetch.
// Méthode 1: fetch() avec then/catch
function chargerDonnees() {
fetch('etudiant.json')
.then(response => {
// VĂ©rifier si la requĂȘte a rĂ©ussi
if (!response.ok) {
throw new Error(`Erreur HTTP: ${response.status}`);
}
return response.json(); // Convertir en JSON
})
.then(data => {
// Traiter les données
console.log('Données chargées:', data);
afficherDonnees(data);
})
.catch(error => {
// Gérer les erreurs
console.error('Erreur:', error);
afficherErreur(error.message);
});
}
// Méthode 2: async/await
async function chargerDonneesAsync() {
try {
const response = await fetch('etudiant.json');
if (!response.ok) {
throw new Error(`Erreur: ${response.status}`);
}
const data = await response.json();
afficherDonnees(data);
} catch (error) {
console.error('Erreur:', error);
afficherErreur(error.message);
}
}
// Méthode 3: fetch() avec options
function chargerAvecOptionsAvancees() {
const controller = new AbortController();
const signal = controller.signal;
// Timeout aprĂšs 5 secondes
const timeoutId = setTimeout(() => {
controller.abort();
}, 5000);
fetch('etudiant.json', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'X-Requested-By': 'Kacper'
},
signal: signal,
cache: 'no-cache',
mode: 'cors'
})
.then(response => response.json())
.then(data => {
clearTimeout(timeoutId);
afficherDonnees(data);
})
.catch(error => {
clearTimeout(timeoutId);
if (error.name === 'AbortError') {
afficherErreur('RequĂȘte annulĂ©e (timeout)');
} else {
afficherErreur(error.message);
}
});
}
Chargement du fichier JSON...
| Méthode | Description | Avantages | Utilisation |
|---|---|---|---|
| fetch() | API moderne pour requĂȘtes HTTP | Promises, simple Ă utiliser | fetch('fichier.json') |
| XMLHttpRequest | Ancienne API pour requĂȘtes | CompatibilitĂ© anciens navigateurs | new XMLHttpRequest() |
| import | Importation de modules ES6 | Syntaxe moderne, typage | import data from './fichier.json' |
| async/await | Syntaxe asynchrone moderne | Code plus lisible, gestion erreurs | async function charger() {} |