Passing BD query by Node for Array in Javascript Front-end

Asked

Viewed 556 times

2

Hello, recently I’m studying a little web programming (I’m very early) and I ended up falling into Node.js, I’m finding everything amazing I’m just having a certain problem, I want to access mysql return a query by Node and pass this JSON to an array in javascript inside ejs (html) front-end, but I’m not getting it, so what am I doing wrong? Follow the BD access code (Obs the connection to the bank is working so I will not insert it here)

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

and 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%>);
  • You can put an example of how you want HTML to come out?

  • This application I’m testing is with Google Maps, the idea is to pass the information of the vector to an object inside the Object Map and display later

  • So you want to pass {lista : results} for a Javascript variable, that’s it?

  • Yes, I don’t know how to go from the database query (Node.js) to the javascript that is in my html file

  • My answer helped?

1 answer

0

Then you can wear it like this:

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

So 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 does JSON.parse making it an object again.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.