【问题标题】:Accessing MongoDB Data in a <script> tag在 <script> 标签中访问 MongoDB 数据
【发布时间】:2019-04-27 06:12:00
【问题描述】:

我将 MongoDB 数据传递到我的 EJS 文件中。我可以使用 HTML 中的 &lt;% %&gt; 标签访问数据。我遇到的问题是我需要访问&lt;script&gt; 标签内的数据,而&lt;% %&gt; 标签不再起作用。

我尝试过的事情:

将数据添加到隐藏输入并使用document.getElementById().value 访问它

我尝试研究在脚本标签中使用 mongo 数据的任何示例,但大多数答案都与 HTML/EJS 中的 &lt;% %&gt; 相关

位置架构

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/…

标签: node.js ejs


【解决方案1】:

试试这个。在您的 app.js 文件中,将 results 渲染为 JSON 字符串,如下所示。

res.render('homePage',{results: JSON.stringify(results)});

现在在你的 homepage.ejs 中使用这个:

const locationResults = <%- results %>

请注意,它可能会在您的 IDE 中导致一些错误,例如“Expression expected .js”。忽略它。可能是 VS Code 与 ejs 文件的兼容性

【讨论】:

  • 我回复了另一个答案,我的问题是我根本不能在我的脚本标签中使用 标签。它返回一个语法错误。不确定原因,但可能是我的 ejs 中的某些东西导致了这个问题,所以我将完整(但很短)的 ejs 添加到主帖
  • 首先,您在 JSON.stringify 分配中忘记了 =。其次,在locationResults 上使用forEach 而不是results
  • 感谢您的帮助,我已经尝试过更改,但即使进行了这些更改,听起来也不会像破记录一样存在由 引起的语法错误。我看到的每个示例都在脚本标签中使用这些,没有任何缺陷。
  • 出现同样的问题。您认为在脚本标签之外添加 > 会起作用吗?编辑:它没有工作
  • 试试const locationResults = JSON.parse('&lt;%- results %&gt;')
【解决方案2】:

我只是写出变量并在函数中使用它

<script>
const locationResults = <%= JSON.stringify(results, null, '\t\) %>;
// Now you don't have to loop in the template, you can loop on the client
locationResults.forEach(location => addMarker({ coords: {lat: location.lat, lng: location.lng}, title: location.title }));
</script>

【讨论】:

  • 也许我不清楚手头的问题。每当我尝试在脚本标签中使用 时,我都会收到语法错误“JS expression expected”。因此,要么我需要弄清楚为什么它不接受标签,要么我需要另一种方式来使用脚本中的数据。所有示例都在 里面工作。我将添加完整的 EJS 文件以便清晰。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-24
  • 1970-01-01
  • 1970-01-01
  • 2015-06-07
  • 2014-01-13
  • 2023-01-09
相关资源
最近更新 更多