Passing query in DB by node to Array in Javascript Front-end

2
Hello, I am currently studying a bit of web programming (I am very exciting) and I ended up falling into node.js, I am finding everything incredible I am just having a certain problem, I want to access mysql return a query by node and pass this JSON for an array in javascript inside the front-end ejs (html), but I'm not getting it, what am I doing wrong? Here is the access code for DB (I'm not going to insert it here)

connection.query('select * from marcadores', function(err, results){
    res.render('map',{lista : results});
});

e Follow the code inside the javascript (front)

var locations = Array();
    <%for(i = 0; i<lista.lenght;i++){%>
        locations.push(<%lista[i].id%>);
        locations.push(<%lista[i].titulo%>);
        locations.push(<%lista[i].latitude%>);
        locations.push(<%lista[i].longitude%>);
    
asked by anonymous 07.07.2016 / 04:33

1 answer

0

In this case you can use this:

<script>
var objeto = JSON.parse('<%-JSON.stringify(lista)%>');
</script>

In this way the object that is passed to the EJS is passed to the HTML inside the script tag and JavaScript will find a string there and make JSON.parse of it making it an object again.

    
09.07.2016 / 17:29