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

277
Visualizações
no se pueden recuperar los datos debido al valor 'indefinido'

En mi sitio web, incluyo películas y series de televisión en las que los usuarios pueden compartir sus comentarios sobre ellas. Los usuarios pueden agregar comentarios, pero cuando se trata de recibir comentarios, se devuelve un valor indefinido. (Estoy tratando de obtener comentarios de movieComment. movieComment almacena comentarios para la película)

 var show = qs["movieId"]; /* show variable is giving my movie's ID and it is 1 */ btnComment.addEventListener('click', (e) => { var movieComment = document.getElementById('textComment').value; push(child(firebaseRef, 'Movies/' + show + '/movieComment/'), movieComment) { movieComment: movieComment }; }); function AddItemsToTable2(comment) { const comments = ` <td>Alan Smith</td> <td><i class="fa fa-star" style="color:rgb(91, 186, 7)"></i></td> <td>${comment}<h6>[May 09, 2016]</h6></td> `; html = comments; body2.innerHTML += html; } } function AddAllItemsToTable2(TheComments) { body2.innerHTML = ""; TheComments.forEach(element => { AddItemsToTable2(element.movieComment); }); } function getAllDataOnce2() { var show = qs["movieId"]; get(child(firebaseRef, 'Movies/' + show + '/movieComment')).then((snapshot) => { var comments = []; comments.push(snapshot.val()); console.log(comments); AddAllItemsToTable2(comments); }); } window.onload = (event) => { getAllDataOnce2(); };

ingrese la descripción de la imagen aquí

Console.log(películas)

ingrese la descripción de la imagen aquí

Error indefinido:

ingrese la descripción de la imagen aquí

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Centrándonos en esta función:

 function AddAllItemsToTable2(TheComments) { body2.innerHTML = ""; TheComments.forEach(element => { AddItemsToTable2(element.movieComment); }); }

El objeto TheComments aquí es un Record<string, string>[] :

 TheComments = [{ "-Mstwhft8fKP6-M2MRIk": "comment", "-Mstwj5P2TD_stgvZL8V": "a comment", "-MstwjxvmkNAvWFaIejp": "another comment" }]

Cuando itera sobre esta matriz, termina con un objeto de elemento que no tiene una propiedad movieComment , por lo que cuando lo alimenta a AddItemsToTable2 obtiene undefined .

Para solucionar esto, debe cambiar la forma en que ensambla el objeto TheComments :

 function AddAllItemsToTable2(TheComments) { // TheComments: ({id: string, text: string})[] body2.innerHTML = ""; TheComments.forEach(commentObj => AddItemsToTable2(commentObj.text)); } function getAllDataOnce2() { const show = qs["movieId"]; get(child(firebaseRef, 'Movies/' + show + '/movieComment')) .then((snapshot) => { const comments = []; snapshot.forEach(childSnapshot => { comments.push({ id: childSnapshot.key, // store this for linking to database/anchors text: childSnapshot.val() }); }); console.log(comments); AddAllItemsToTable2(comments); }); }

Como otro punto, tenga cuidado con los riesgos de XSS al usar innerHTML y use innerText siempre que sea posible para cualquier contenido generado por el usuario. Además, debe envolver el contenido de su comentario en una fila de la tabla para que los comentarios se concatenen correctamente.

 function AddItemsToTable2(commentObj) { const commentEle = document.createElement('span'); commentEle.id = `comment_${commentObj.id}`; commentEle.innerText = commentObj.text; const commentRowHTML = ` <tr> <td>Alan Smith</td> <td><i class="fa fa-star" style="color:rgb(91, 186, 7)"></i></td> <td>${commentEle.outerHTML}<h6>[May 09, 2016]</h6></td> </tr>`; body2.innerHTML += commentRowHTML; } function AddAllItemsToTable2(TheComments) { body2.innerHTML = ""; TheComments.forEach(commentObj => AddItemsToTable2(commentObj)); }

Con el bloque de código anterior, ahora puede agregar #comment_-MstwjxvmkNAvWFaIejp al final de la URL de la página actual para vincular al comentario "otro comentario" directamente de forma similar a como StackOverflow vincula a los comentarios.

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