0

I want my server to send a JSON object to a javascript on the client's side. How can the client get the object into his javascript and not show the object on screen?

In my server :

app.get('/', function (req, res) {
    res.send(jsonObj);
});

Thank you!

pah
  • 4,700
  • 6
  • 28
  • 37
asdsd
  • 99
  • 1
  • 9

2 Answers2

2

Using jquery i will show you a quick example of how things work:

Client

$.get('youserver.com/', {mydata: 'content'}, function(response){
   //callback triggered when server responds
   console.log(JSON.stringify(response));
});

Server

app.get('/', function (req, res) {
  if(req.params.mydata === 'content'){
    res.end("you sent content");
  }  else {
    res.end("you sent something else");
  }
});

Do you understand what i mean?

Max Bumaye
  • 1,017
  • 10
  • 17
  • can you explain a little more? what is req.params.mydata==='content' and what is res.end. sorry i dont know much - i'm pretty new to node.js. Thank you for your answer – asdsd Dec 10 '14 at 13:04
  • you also seem to be new to javascript then :) "req" is the parameter object which passes request variables from the http layer to your express route. params is an object nested inside the req object which consists of your parameters passed with the request. mydata is the data string you have passed on the client side. you might want to "npm install body-parser" (and also read through its docs of course) basicly this is just a communication set up between your client/server. You should read how this works in detail in some tutorial for example on scotch.io – Max Bumaye Dec 10 '14 at 13:10
  • hhh .i'm relativly new. I started learning it 2 week ago this semester. Anyway thank you very much!. – asdsd Dec 10 '14 at 13:12
  • Its easy to learn the basics, just have a look at how the javascript stack works. Check out some articles on http and just find out stuff by simple testing :) good luck – Max Bumaye Dec 10 '14 at 13:18
0

Try to use res.json() method

app.get('/', function (req, res) {
    res.json(jsonObj);
});
Vitalii Zurian
  • 17,858
  • 4
  • 64
  • 81