Reputation: 345
This question follows this one: Get data from Node.js via Express.
I have a server with Node.js and I use Express to build a web app. My server is already able to building an array from a database using a function (rss_interrogDB). Now I want to use this array to display a list in an html page. I already have a script in my page html that can create a list from a given array.
But my problem is that I don't know to allow the html file to use this array in this function...
I have this on my server code:
app.get('/', function(req, res) {
rss_interrogDB(function(serverData) {
res.send(serverData);
});
});
And this on my html file:
$.get('/').success(function(serverData) {
// TO DO something with serverData
}).error(function(serverData, status) {
// error handling
});
But, doing this, the html directly displays the array although I want to use it to build the html code... Is the pb in the res.send(serverData)? What do I have to write in the "TO DO something with serverData" part in the html file?
Upvotes: 1
Views: 4297
Reputation: 2470
EJS http://embeddedjs.com/ is a good approach. Your post doesn't show the array you want to use, so here's the example from the EJS home page. Say you have the following object:
var myObject = { title:'Cleaning Supplies', supplies:['mop','broom','duster'] }
Then you can write a template file, which is basically HTML with JavaScript code embedded into tags (similar to the way PHP works), to loop through your array:
<ul>
<% for(var i=0; i<supplies.length; i++) {%>
<li><%= supplies[i] %></li>
<% } %>
</ul>
Notice there is no script
tag.
Next you'll set up the ejs module in node and tell it to render the view with your object:
app.get('/my/url', function(req, res, next){
res.render('template.ejs', myObject );
});
And that will produce html like this that gets sent to the browser:
<ul>
<li>mop</li>
<li>broom</li>
<li>duster</li>
</ul>
Here's a more detailed example: http://superbigtree.tumblr.com/post/62759231807/a-simple-example-application-using-express-ejs-and
Upvotes: 3