Skip to content Skip to sidebar Skip to footer

Server Sends Data To Client

In my express project I want my server to send a JSON object to the client. The client uses a script to display the data it recieves and so I dont want to the data sent from the se

Solution 1:

On your server, use res.json({data:'text'}); instead of res.render(...) to send json. That should do the trick.

Update:

If you want to build a single page application with multiple ajax requests you should use different routes for those. One will send the page and the other the data.

However, if your application is small and simple, you could continue doing what you did, but get the data via javascript variable instead of an ajax request. For that in your template you'll have to do something like that (assuming it's jade):

script(type='text/javascript')                                                   
  var local_data =!{JSON.stringify(data)};

The page will be rendered with the following HTML:

<scripttype="text/javascript">var local_data = {"data":"text"};
</script>

You than in your script can do the following:

//Your javascript 

function displayPage(data){
     //display logic here
     console.log(data);   
}

displayPage(local_data);

Post a Comment for "Server Sends Data To Client"