zero0o0o zero0o0o - 3 months ago 23
Node.js Question

How do I use backend variable in ejs script section?



<!-- begin snippet: js hide: false console: true babel: false -->

<script>
// initialize the map
var map = L.map('map').setView([25.037393872113785, 121.56372070312499], 12);
// load a tile layer
var baseLayer = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{
attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
maxZoom: 17
}).addTo(map);

var Data =
var cfg = {
"radius": 0.03,
"maxOpacity": 0.5,
"scaleRadius": true,
"useLocalExtrema": true,
latField: 'lat',
lngField: 'lng',
valueField: 'count'
};

var heatmapLayer = new HeatmapOverlay(cfg).addTo(map);
heatmapLayer.setData(Data);

</script>





//javascript version = 1.7
var express = require('express');
var router = express.Router();
var r = require('rethinkdb');
var rethinkdbHost = "140.109.18.136";
var connection = null;
var waterfall = require('async-waterfall');

r.connect( {host: rethinkdbHost, port: 28015}, function(err, conn) {
if (err) throw err;
connection = conn;
r.db('AQI_inference').table('pm25_one_week')).run(connection, function(err, cursor) {
if (err) throw err;
cursor.toArray(function(err, result) {
if (err) throw err;
var cor = result.geometry.coordinates;
var t = result.properties.time;
var pm25 = result.properties.col;
console.log(cor, t, pm25);
router.get('/', function(req, res, next) {
res.render('mapTest', {cor: cor,time: t, pm25: pm25});
});
});
});
});




I just learned nodejs express for a week

I want to make a map with air quality mark on it and got some problem now,

I get data from rethinkDB and I can only access the data with <% =%>

How do I use the variable cor, time and pm25 in frontend script section?

I want to use cor in 'var Data' in my js code.

is there any simple way to do this?

please help me

Answer

use some element for storing data elements.

<div id="script" data-time="<%= time %>" data-cor="<%= cor %>"></div>

In you script tag you can access using

var time = document.getElementById("script").getAttribute('data-time');

similarly you can use other variables.