Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda