Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

151
Vistas
Because I only see the last element of the for loop

I'm having a problem; I have the following program code:

var xmlhttp = new XMLHttpRequest();
var url = "https://wjko5k6250.execute-api.us-east-2.amazonaws.com/motorcycle"; 
xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
   var allmot = JSON.parse(this.responseText);
   console.log(allmot);
    for(var i = 0, len = allmot.Items.length; i < len; i++)
    {
      id=allmot.Items[i].id
      var url1 = "https://wjko5k6250.execute-api.us-east-2.amazonaws.com/motorcycle/"+id; 
      console.log(url1);
      xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          var myArr = JSON.parse(this.responseText);
          console.log(myArr);
          document.getElementById("img").src = myArr.Item.image;
          document.getElementById("brd").innerHTML = myArr.Item.brand;  
        }
      };
      xmlhttp.open("GET", url1, true);
      xmlhttp.send();
    }
  }
};
xmlhttp.open("GET", url, true);
xmlhttp.send();

allmot is as follows:

Items: Array (4)
0: {brand: 'Guzzi', id: '123456', image: 'moto_guzzi.jpg', date: '27/11/2021 '}
1: {brand: 'Bimota', id: '135623', image: 'bimota.jpg', date: '04/12/2021 '}
2: {brand: 'Ducati', id: '123789', image: 'b_desertx.jpg', date: ' 04/12/2021 '}
3: {brand: 'Benelli', id:' 146975 ', image:' benelli.jpg ', date: '27/11/2021'}

url1 returns (according to the for loop):

https://wjko5k6250.execute-api.us-east-2.amazonaws.com/articles/123456
https://wjko5k6250.execute-api.us-east-2.amazonaws.com/articles/135623
https://wjko5k6250.execute-api.us-east-2.amazonaws.com/articles/123789
https://wjko5k6250.execute-api.us-east-2.amazonaws.com/articles/146975

and so far everything seems to be fine.

The problem is in myArr; I noticed that it returns the image and brand of the last element only, so the one that has id equal to 146975.

Therefore there seems to be problems with the for loop.

Can anyone kindly help me? Thank you all.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

As first correction I'd not recycle the XHR object from the outer loop in the inner loop.

When you say xmlhttp.onreadystatechange = function() ... in the inner loop, the xmlhttp is already in the readystate, obtained in the outer loop.

So, without further checking what is going on, I'd use two XHR objects (maybe like outerXmlhttp and innerXmlhttp). I'd also recreate the inner XHR for every cycle with:

var innerXmlhttp;

at the top of the outer closure.

Then, inside the cycle do:

innerXmlhttp = new XMLHttpRequest();

This is because of variable hoisting. If you just do this:

var innerXmlhttp = new XMLHttpRequest();

inside the cycle you may get a different behaviour. Just don't do it and write what you mean (hoist variables and assign them where you actually need it).

If all of this isn't enough ask a new, more precise question about what is going on.

This is your code with the corrections:

var outerXmlhttp = new XMLHttpRequest();
var url = "https://wjko5k6250.execute-api.us-east-2.amazonaws.com/motorcycle"; 
outerXmlhttp.onreadystatechange = function() {
  var innerXmlhttp;

  if (this.readyState == 4 && this.status == 200) {
   var allmot = JSON.parse(this.responseText);
   console.log(allmot);
    for(var i = 0, len = allmot.Items.length; i < len; i++)
    {
      id=allmot.Items[i].id
      var url1 = "https://wjko5k6250.execute-api.us-east-2.amazonaws.com/motorcycle/"+id; 
      console.log(url1);

      innerXmlhttp = new XMLHttpRequest();
      innerXmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          var myArr = JSON.parse(this.responseText);
          console.log(myArr);
          document.getElementById("img").src = myArr.Item.image;
          document.getElementById("brd").innerHTML = myArr.Item.brand;  
        }
      };
      innerXmlhttp.open("GET", url1, true);
      innerXmlhttp.send();
    }
  }
};
outerXmlhttp.open("GET", url, true);
outerXmlhttp.send();

EDIT: @Teemu's eagle eye

As @Teemu points out in his comment, if you reassign values over and over to the same DOM objects like this:

document.getElementById("img").src = myArr.Item.image;
document.getElementById("brd").innerHTML = myArr.Item.brand;  

you're clearly overwriting whatever value was there before. Instead, you should create and append those DOM objects, more like this:

var img = document.createElement("img");
img.src = myArr.Item.image;
var brd = document.createElement("p");
brd.innerText = myArr.Item.brand;
document.getElementById("motlist").append(img);
document.getElementById("motlist").append(brd);

Obviously, you'll need a <div id="motlist"></div> element or some other parent in the DOM to which to append the new elements.

For paging you may also want to clear those elements in the list... but here we're going overboard.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda