how to create an HTML element in JavaScript

0

I have an ajax function that gets the elements of a data source in django. I can see that the function brings the elements in the inspector but I can not create the element in the div that I need.

the result of the ajax function in the inspector:

[{nombre: "gato", imagen: "/media/1swGj9_7oxrYGA.jpg", duracion: "2000"},…]
0 : {nombre: "gato", imagen: "/media/1swGj9_7oxrYGA.jpg", duracion: "2000"}
1 : {nombre: "lay", imagen: "/media/layout_53hUG5g.png", duracion: "2000"}
2 : {nombre: "lol", imagen: "/media/IMG_194935_jkGCdbp.jpg", duracion: "2000"}

    duracion :"2000"
    imagen : "/media/IMG_194935_jkGCdbp.jpg"
    nombre : "lol"

my HTML

<div class="wrapper">
    <ul class="bxslider" id="datos">
    <!--     {% for img in imagenes %}
        <li id="images">
            <img src="{{ img.imagen.url }}" data-id="{{ img.id }}" >
        </li>
    {% endfor %} -->
    </ul>
</div>

my JS:

<script>
    $('.bxslider').bxSlider({
      onSliderLoad: function(){
        // do funky JS stuff here
        // alert('Slider has finished loading. Click OK to continue!');
        console.log('<--------------------- se dispara el evento? ');
        $.ajax({
            url: '/image/busqueda',
            type: 'get',
            datatype: 'json',
            success : function(data){
                var html = ""
                for(var i = 0 ; i < data.lenght; i ++){
                    html += '<li><img src="'+ data[i].fields.imagen + '" data-id="' + data[i].fields.id + '"/></li>';
                }
                $('#datos').html(html);
            }
        });

      }
    
asked by victor reyes1 20.09.2017 в 21:51
source

1 answer

0

Your code seems to work, I only see an error when typing the word length , you put lenght which gives undefined and your cycle for never iterate.

I put here a code a little easier to read using the function 'append' of jQuery which inserted into the element #datos

var data = [
  {id: "gato", imagen: "/media/1swGj9_7oxrYGA.jpg", duracion: "2000"},
  {id: "lay", imagen: "/media/layout_53hUG5g.png", duracion: "2000"},
  {id: "lol", imagen: "/media/IMG_194935_jkGCdbp.jpg", duracion: "2000"}
]

function crearHTML() {
  for (var i = 0; i < data.length; i++) {
    $('#datos').append('<li><img src="' + data[i].imagen + '" data-id="' + data[i].id + '"/>'+ data[i].id + '</li>')
  }

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button onClick="crearHTML()">Crear HTML</button>

<div class="wrapper">
    <ul class="bxslider" id="datos">
    <!--     {% for img in imagenes %}
        <li>
            <img src="{{ img.imagen.url }}" data-id="{{ img.id }}" >
        </li>
    {% endfor %} -->
    </ul>
</div>
    
answered by 22.09.2017 / 21:35
source