5
Hi, guys. I’m doing this: A system where the user can shuffle the order of the images.
Click the button and randomly they change places.
So far so good, the problem is that when I get back and play pro javascript, it only takes one element. Follow the code below.
PHP:
<?php
/*
*
*essa lista será buscada de forma
*dinâmica pelo banco de dados e
*gerado um array
*
*/
$playlist = [
"e_amor.mp3",
"dancando_lambada.mp3",
"lambada.mp3",
"anjo_azul.mp3",
"acarta.mp3",
"amor_de_julieta_e_romeu.mp3"
]; //lista de músicas
/*
*
*gera a nova playlist e envia o callback ao cliente
*
*/
shuffle($playlist); // gera a nova playlist
$new_playlist = []; //array vazio
foreach($playlist as $list){
$new_playlist[] = $list;
}
echo json_encode(array('response' => $new_playlist));
JAVASCRIPT:
$().ready(function(){
$('body').on('click', "#shuffle", function(){
$.ajax({
url: 'data.php',
type: 'POST',
dataType: 'json',
cache: true,
success: function(e){
var html;
for(var i = 0; i < e.response.length; i++){
console.log(e.response[i]); //Console funciona, só o html que não pega tudo.
html = "<li>" + "<a href='"+ e.response[i] +"'>" + e.response[i] + "</a>" + "</li>";
}
$('.list').html(html);
}
});
});
});
HTML:
<!DOCTYPE>
<html>
<head>
<title>Playlist</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="playlist">
<ul class="list" style="list-style:none; float:left;">
<li><a href="#">e_amor.mp3</a></li>
<li><a href="#">dancando_lambada.mp3</a></li>
<li><a href="#">lambada.mp3</a></li>
<li><a href="#">anjo_azul.mp3</a></li>
<li><a href="#">acarta.mp3</a></li>
<li><a href="#">amor_de_julieta_e_romeu.mp3</a></li>
</ul>
</div>
<div style="clear:both;"></div>
<button id="shuffle">Embaralhar playlist</button>
<button>Salvar</button>
<button>Deletar selecionadas</button>
<!--SCRIPT-->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="function.js"></script>
</body>
</html>
I tried to put the $('.list').html(html);
within the loop of repetition;
At times
html =
forehead withhtml +=
– Sergio
It worked. Thank you. Really lack of attention.
– Alex
Great. I put an answer too, because in addition to being useful to others I suggest using the
reduce
in such cases.– Sergio
I’ll mark it as best. Only the system won’t release for another 8 minutes. Thank you.
– Alex
just one more little detail, the
shuffle()
already changes the variable$playlist
so there is no need to copy the contents of$playlist
for$new_playlist
. You can skip the whole step and put one rightecho json_encode(array('response' => $playlist));
.– Neuber Oliveira
I had fixed it, so much so that I already did it. Thank you.
– Alex