Soy completamente nuevo en javascript y desarrollo web.
Tengo un problema con el ciclo for; lo que me pasa es que los id me regresan todos juntos y no individualmente para poder recuperar la imagen y el titulo relativo a traves del id, entonces no puedo recuperar imagenes y titulo del arreglo json.
Específicamente me sale el error:
TypeError no capturado: no se pueden leer las propiedades de undefined (leyendo 'immagine') en XMLHttpRequest.xmlhttp.onreadystatechange
Advertencia: no tengo problemas en cómo recuperar elementos en una matriz json porque sé cómo hacerlo muy bien
Este es mi código:
//here I get all the articles, so my json array var xmlhttp = new XMLHttpRequest(); var url = "https://wjko5u1234.execute-api.us-east-2.amazonaws.com/articles"; xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var allart = JSON.parse(this.responseText); var container=document.getElementById("slideshow") for(var i = 0; i < allart.Items.length; i++) { container.innerHTML += '<div class="slideshow-container"></div>'; document.getElementById("id").innerHTML += "<br/>" + allart.Items[i].id; myFunction1(allart.Items[i].id); } } }; xmlhttp.open("GET", url, true); xmlhttp.send(); //here I pass the id via function call, and for each id I want to retrieve image and title which has that specific id only i get the set of ids without having one at a time to retrieve what i need function myFunction1(id) { var xmlhttp = new XMLHttpRequest(); var url = "https://wjko5u1234.execute-api.us-east-2.amazonaws.com/articles/"+id; xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myArr = JSON.parse(this.responseText); console.log(myArr); document.getElementById("img1").src="articoli_img/"+myArr.Item.immagine; document.getElementById("title1").innerHTML = myArr.Item.titolo; } }; xmlhttp.open("GET", url, true); xmlhttp.send(); }Estaría muy agradecido por cualquier ayuda.
Parece que la propiedad "Item" no existe en el objeto devuelto (ubicado en myFunction1() ) (¿quiso escribir myArr.immagine?)
Como eres nuevo: recomiendo usar bucles for-each en colecciones, usando:
for(let item of allart.Items) { ..... }