Insert multiple html with ajax

0

I have the following code in jquery:

musicas: function(){
    $.ajax({
        url: 'assets/includes/oloco.php',
        type: 'GET',
        dataType: 'json',
        beforeSend: function(){
            efeito.inicio();
        },
        success: function(data){
            $('.texto').html(data[0].musica);
            efeito.fim();
        }
    }),
    setTimeout(function(){
        player.musicas();
    }, 15000);
}

And in the html as seen I have:

 <div class="text"></div>

However, my current ajax only changes the text of the div, I would like to add 5 divs by changing the date []! The oloco.php request is in json and has exactly 5 values as you can see below:

[
{
    "musica": "Luan Santana  Acordando o Pr\u00e9dio - Make U Sweat Remix (Lyric Video)"
},
{
    "musica": "Kygo ft. Parson James - Stole the show (Lyrics video)"
},
{
    "musica": "Justin Bieber Ft Daddy Yankee y Luis Fonsi - Pasito a Pasito Suave Suavecito (Letras)"
},
{
    "musica": "Jhef - Vida M\u00edtica (Official V\u00eddeo)"
},
{
    "musica": "Jhef - Pode ser n\u00f3s dois (Official Video)"
}
]

How can I insert multiple divs with different values and in order?

    
asked by anonymous 09.05.2017 / 01:58

1 answer

1

Just you iterate over the result of the AJAX request and use the append function of jQuery to insert the element into the DOM. It should look like this:

musicas: function(){
    $.ajax({
        url: 'assets/includes/oloco.php',
        type: 'GET',
        dataType: 'json',
        beforeSend: function(){
            efeito.inicio();
        },
        success: function(data){

            // Exclui possíveis músicas anteriores:
            $('.texto').html("");

            // Itera sobre todos os elementos de data:
            $(data).each(i => {
                // Cria um novo elemento p:
                let element = $("<p>");
                // Define o conteúdo de p:
                element.html(data[i].musica);
                // Adiciona o novo elemento ao DOM:
                $('.texto').append(element);
            });

            efeito.fim();
        }
    }),
    setTimeout(function(){
        player.musicas();
    }, 15000);
}
    
09.05.2017 / 02:07