简体   繁体   中英

For loops not working in Javasctipt for a declared variable from node.js in Jade

I am learning to work with node.js and JADE and am having problem with making the for loop work in a javascript within a jade file. I am trying to learn it with a simple code. I am passing an array from my database to the jade file. it works when I directly call a specific element of the array (var x = !{lat[2]}; alert(x), but it won't work when I put it in the for loop. here is my app.js code:

app.get('/test', function(req, res){

getlat(function(err, lat){
    if(err){
      return res.send(500);
    }console.log(lat);
    res.render('test', {lat:lat});
  });

and this is where the lat is being retrieved from the database:

var mongoose = require ('mongoose');
  function getlat(callback){
  var lat = new Array();
  mongoose.model('stories').find({},function(err, companies) {
    if(err){
      return callback(err, lat);
    }
    for (var i = 0; i < companies.length; i++) {
      lat[i] = companies[i].Lat;
    }
    return callback(null, lat);
 });
}
module.exports = getlat;

and here is my jade file:

body
   button.btn.btn-info Click Here! 
script.
  $('button').click( function() {
    for (var i = 0; i < 2; i++) {
      var x = !{lat[i]};
      alert(x);
    });
  });

I would really appreciate it if someone tells me where I am making a mistake. Thanks

The issue is that lat only exists server-side while i only exists client-side.

Despite both using JavaScript, the 2 environments are still managed separately from each other, with all of the server-side code running to completion before the client-side code begins.

One option to resolve this is to output the entirety of lat to a client-side variable in the view, using JSON and JavaScript's shared syntax, and iterating over it client-side.

script.
  $('button').click(function () {
    var lat = !{ JSON.stringify(lat) };

    for (var i = 0; i < 2; i++) {
      // ...
    }
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM