Question: print variable returned by server in node.js

Question

print variable returned by server in node.js

Answers 1
Added at 2016-12-22 18:12
Tags
Question

I'm creating a node.js app.

I have a list with 4 types of movies (see below).

When I click one of these types I make a call to the server, then the server retrieves from a database the movies of that type and sends me back the result. On my client side I can correctly see the result the server has sent me but I can't loop over the result in order to print all the movies to the screen.

<ul>
  <li id="Animation">Animation</li>
  <li id="Action">Action</li>
  <li id="Comedy">Comedy</li>
  <li id="Drama">Drama</li>
</ul>
<ul>
<% movies.forEach(function(movie){ %>  // doesnt work 
    <li><%= movie.id %> - <%= movie.title %></li>
<% }) %>
</ul>

<script>
$( document ).ready(function() {
  $('li').click(function(){
    var movieType = $(this).attr('id');
    $.post('findMovies', { type: movieType}, function(data){
        console.log(data);  // I see the array correctly in browser's console
        var movies = data;
      });
  });
});
</script>
Answers
nr: #1 dodano: 2016-12-22 19:12

Loop inside your post callback function:

...
$.post('findMovies', { type: movieType}, function(data){
    data.forEach(function(movie){
        var li = $('<li/>')
            .text(movie.id + ' - ' + movie.title)
            .appendTo(ulRef);//assuming ulRef is a reference to the ul element above
    });
});
...

Your code doesn't work because

<% movies.forEach(function(movie){ %>  
    <li><%= movie.id %> - <%= movie.title %></li>
<% }) %>

is not reprocessed after "post" completes.

Source Show
◀ Wstecz