【发布时间】:2019-04-27 06:12:00
【问题描述】:
我将 MongoDB 数据传递到我的 EJS 文件中。我可以使用 HTML 中的 <% %> 标签访问数据。我遇到的问题是我需要访问<script> 标签内的数据,而<% %> 标签不再起作用。
我尝试过的事情:
将数据添加到隐藏输入并使用document.getElementById().value 访问它
我尝试研究在脚本标签中使用 mongo 数据的任何示例,但大多数答案都与 HTML/EJS 中的 <% %> 相关
位置架构
const locationSchema = new Schema({
lat: String,
lng: String,
title: String
});
app.js
app.get('/', function(req,res){
Locations.find({}, (err, results) => {
if (err) {
return res.render.status(500).send('<h1>ERROR</h1>');
} else{
console.log(results)
res.render('homePage',{results, Locations, req});
}
});
});
ejs
<!-- ejs_views/homePage.ejs -->
<!doctype html>
<html lang = "en">
<!-- displays head.ejs-->
<head>
<% include head %>
<style>
#map{
height:400px;
width: 100%;
}
</style>
</head>
<!-- displays header.ejs-->
<body class = "container">
<header>
<% include header %>
</header>
<!-- Edit the body of the front end here-->
<main>
<div class = "jumbotron">
<h1>This is great</h1>
<p>Testing out EJS</p>
</div>
<div id = "map"></div>
<% for (const location of results) { %>
<h1> <%= location.title %></h1>
<h1> <%= location.lat %></h1>
<h1> <%= location.lng %></h1>
<% } %>
<script>
function initMap(){
//SYNTAX ERROR HERE ON <% AND %>
const locationResults = <% JSON.stringify(results) %>;
//Map Options to dictate zoom and position
var options = {
zoom: 16,
center: {lat:35.6543936, lng: -97.4714266}
}
//init map for view
var map = new google.maps.Map(document.getElementById('map'), options);
/*var marker = new google.maps.Marker({
position:{lat: 35.654243, lng: -97.472937 },
map: map,
title: 'Math And Computer Science'
});*/
//addMarker({coords:{lat:35.6543936, lng: -97.4714266}, title: "TestCase"});
//iterateFunc();
results.forEach(location => addMarker({coords: {lat: location.lat,lng: location.lng}, title: location.title}))
//Add Marker Function
function addMarker(props){
var marker = new google.maps.Marker({
position: props.coords,
map:map,
title: props.title
})
}
}
</script>
</main>
<!-- displays footer.ejs-->
<footer>
<% include footer %>
</footer>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAftGHvJnejXQm5k1jiLiBRsRwm5SXqzm8&callback=initMap">
</script>
</body>
</html>
预期结果:
能够在我的脚本中循环遍历 mongodata 并在 addMarker 函数中使用它
实际结果::[
【问题讨论】:
-
“ 标签在 html 标签中不再起作用”是什么意思?
-
脚本标签内。我猜 S.O 从我的帖子中删除了“
-
我也尝试了这个帖子的解决方案,但没有成功stackoverflow.com/questions/16098397/…