I am trying to populate a dropdown in my index html with data from a mongodb collection. I have populating code that looks like this:
<script>
document.addEventListener("DOMContentLoaded", function() {
for (element in mongoData){
var option = document.createElement('option');
option.innerHTML = element;
option.value = element;
document.getElementById('Active_Sessions').append(option);
}
});
</script>
and in app.js, my route is as follows:
app.use("/",(req,res) => {
res.sendFile(__dirname + "/index.html")
})
I need to pass the JSON object 'mongoData' to this html, and am not sure how to do this. The 'mongoData' will be a JSON of some data collected from a given collection.
One solution I thought of but haven't implemented yet is to write out this mongodata to a text file or a csv file or something like that from the app.js, and then read in the file from my populating script. I feel like this would be bad form though and not very secure.
Another option I thought of is to try and connect to the mongoose server within the populating script, but when I tried this, it didn't work so I've kinda assumed that this is not possible.
Something I've looked into before posting this is using res.render() to send the JSON, but I don't really understand what templating is and would rather not have to learn about all of that if I can avoid that.
Is there an elegant solution to this?
You would change your data in your server eg through a template engine.
Or you can build something similar to do the same. Dummy logic:
UPDATE: A simple example for a custom template engine.
First a simple html file - index.html (please notice $replace_me):
<html>
<body>
<div class="circle">
$replace_me
<div class="square">
something else
</div>
</div>
<body>
</html>
In our node server we could do something like this:
var fs = require('fs');
//used sync for clean demo, use async in production
var _html_cont = fs.readFileSync('index.html', {encoding: 'utf-8'});
//dynamic content to replace
var _repl = "<div>I am new!</div>";
//actually replace it
var _im_regex = new RegExp("\\$replace_me", "gm");
_html_cont = _html_cont.replace(_im_regex, _repl);
//send result to client
res.writeHead(200, { 'content-type': 'text/html' });
res.write(_html_cont);
res.end();
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加