Problem with name generator in javascript

2

Hi, I'm doing a course and one of the projects is a name generator that we made using this api link ?, I could finish it but the problem is that when I want to generate more than one name at a time (since I can select generate up to 15) several of these names are repeated, I leave my code below

document.querySelector('#generar-nombre').addEventListener('submit', cargarNombres);

// Llamado a Ajax e imprimir resultados
function cargarNombres(e) {
     e.preventDefault();

     // Leer las variables

     const origen = document.getElementById('origen');
     const origenSeleccionado = origen.options[origen.selectedIndex].value;

     const genero = document.getElementById('genero');
     const generoSeleccionado = genero.options[genero.selectedIndex].value;

     const cantidad = document.getElementById('numero').value;



     let url = '';
     url += 'http://uinames.com/api/?';
     // Si hay origen agregarlo a la URL
     if(origenSeleccionado !== '') {
          url += 'region=${origenSeleccionado}&';
     }
     // Si hay un genero agregarlo a la URL
     if(generoSeleccionado !== '') {
          url += 'gender=${generoSeleccionado}&';
     }
     // Si hay una cantidad agregarlo a la URL
     if(cantidad !== '') {
          url += 'amount=${cantidad}&';
     }
     // Conectar con ajax
     // Iniciar XMLHTTPRequest
     const xhr = new XMLHttpRequest();
     // Abrimos la conexion
     xhr.open('GET', url, true);
     // Datos e impresion del template
     xhr.onload = function() {
          if(this.status === 200) {
               const nombres = JSON.parse( this.responseText ) ;
               if (typeof(nombres) === 'Object')  {
                    nombres = [nombres];
               // Generar el HTML
               let htmlNombres = '<h2>Nombres Generados</h2>';

               htmlNombres += '<ul class="lista">';

               // Imprimir cada nombre
               nombres.forEach(function(nombre) {
                    htmlNombres += '
                              <li>${nombre.name}
                    ';
               });

               htmlNombres += '</ul>';

               document.getElementById('resultado').innerHTML = htmlNombres;
          }}
     }
     // Enviar el Request
     xhr.send();

}
    
asked by pablo calofatti 18.12.2018 в 21:58
source

1 answer

0

For what I can appreciate, your code is fine. If the names are repeated, it is because the API that you are using generates them repeated. You have 3 options:   1. Filter the list of names you are receiving as a response from the API and leave out the repeated ones.   2. Change API and start using a q that does not generate repeated names.   3. Modify the code of said API so that it does not return repeated names.

The most viable option seems to be the first one. Good luck!

    
answered by 18.12.2018 в 23:50