Test API Random User

Utilisation de l'API Random User pour générer des utilisateurs

by philBou

HTML

<!DOCTYPE html>
<html>

  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width" />
   <title>API Random Contacts Tests</title>
  </head>
  <body>
    <h1>
      Démo avec la méthode fetch()
    </h1>
     <section>
        <h2>
          20 contacts aléatoires
        </h2>
        <table>
          <thead>
              <tr>
                  <th colspan="2">Liste des contacts</th>
              </tr>
              <tr>
                  <th>Photos</th>
                  <th>Prénom/Nom/Email</th>
              </tr>
          </thead>
          <tbody id="contact">
          <!-- ici traité avec javascript -->
          </tbody>
        </table>        
    </section>
  </body>
</html>

CSS

body {
  background-color: #DC7633;
}

ul {
  list-style: none;
}
  table,
      td,
      th {
        padding: 10px;
        border: 2px solid #1c87c9;
        border-radius: 5px;
        background-color: #e5e5e5;
        text-align: center;
      }
 th {
   background-color: #3498DB;
 }
 td {
   background-color: white;
 }

JavaScript

const ul = document.getElementById('auteurs'); // pour des tests...
const tbody = document.getElementById('contact'); // dans un joli tableau
const url = 'https://randomuser.me/api/?results=20'; // 20 par défaut

async function charger() {
await fetch(url)
  .then(response => response.json())
  .then(data => {

    // ici on traite les données json
    let contacts = data.results; // results est le tableau des contacts fictifs générés
    return contacts.map(function(contact)
    {
			let img = nouveauNoeud('img');
      let p = nouveauNoeud('p');
      img.src = contact.picture.medium;
      p.innerHTML = `${contact.name.first}  ${contact.name.last}<br>${contact.email}`;
       // ajout dans le tableau
      ajouter(img, p);
    })

  })
  .catch(error => {
    console.log(error)
  });
}

// Fonction qui reçoit une balise img et p déjà prêtes
async function ajouter(image, paragraphe) {

   let tr = nouveauNoeud("tr");  // ligne
    // 2 cellules par contact
    for (let colonne = 0; colonne < 2; colonne++)
    {
      let td = nouveauNoeud("td");
      
      if(colonne == 0 )
      {
      	// on y met la photo
         ajouterAuParent(td, image);
      }
      else
      {
      // on y met le paragraphe
       ajouterAuParent(td, paragraphe);
      }
      // on ajoute la cellule à la ligne
      ajouterAuParent(tr, td);
    }
    // on ajoute notre ligne complète à notre body du tableau 
    ajouterAuParent(tbody, tr);
}

// fonctions annexes
function nouveauNoeud(element) {
  return document.createElement(element);
}

function ajouterAuParent(parent, element) {
  return parent.appendChild(element);
}

charger();