Popular list-group bootstrap with ajax

1

Hello, everyone.

I'm trying to popular a list-group bootstrap with ajax but I'm not getting it. I have already researched several places about it and could not resolve it.

The php code is ok and the json that returns from php is also ok.

Follow the html code

<!DOCTYPE html>
<html>
<header>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="robots" content="noindex, nofollow">
<link rel="stylesheet" href="css/bootstrap.min.css"/>
<script type="text/javascript">
$(document).ready(function(){
$('#lista').empty();
$.ajax({
    type:'GET',
    url: 'artigos.php',
    dataType: 'json',
    success: function(dados){
        for(var i=0;dados.length>i;i++){
            $('#lista').append('<a href=\"artigos/'+dados[i].link+'?id='+dados[i].id'\" class=\"list-group-item\">'+dados[i].titulo+'</a>');
        }
    }
});
});
</script>
</header>
<body>
<div class="page-header text-center">
<h1>Artigos <br /><small>Selecione um item para ler o artigo</small></h1>
</div>
<div class="list-group" id="lista">

</div>
<script src="js/jquery-3.2.1.min.js"></script>
</body>
</html>
    
asked by anonymous 29.10.2017 / 22:56

2 answers

2

You are escaping unnecessary quotes and generating invalid HTML.

Instead of \" you should only have " once you start the strings with simple ' .

Then it changes

$('#lista').append('<a href=\"artigos/'+dados[i].link+'?id='+dados[i].id'\" class=\"list-group-item\">'+dados[i].titulo+'</a>');

(and correcting the + missing in +dados[i].id' ), to:

$('#lista').append('<a href="artigos/' + dados[i].link + '?id=' + dados[i].id + '" class="list-group-item">' + dados[i].titulo + '</a>');
    
29.10.2017 / 23:00
2

In addition to the issues mentioned in the @Sergio response, there is another error in your code that is the cause of the problem: you are loading jQuery at the end of the document, after the code.

Load the jQuery library preferably into% of document%:

<head>
<script src="js/jquery-3.2.1.min.js"></script>
</head>
    
29.10.2017 / 23:14