climboid
climboid

Reputation: 6952

ajax response for node file

so still a newb to nodeJS and back end code in general. I need some help with ajax and node. For instance I have a function that goes like this

function random(response) { 
  var objToJson = {...};
  response.write(objToJson);
  response.end();
}

if instead of writing I want to pass this json object to another function as a response of an ajax call made to it how would that be?

Thanks for you help!

Upvotes: 0

Views: 547

Answers (2)

ryanjduffy
ryanjduffy

Reputation: 5215

It sounds like you want to return a javascript object to work with in your client-side code. While that's not possible directly (you can't send an object directly over HTTP; you're always serializing/deserialing in some fashion), you can certainly return a JSON payload and easily convert that to an in-memory javascript object. If that's what you're doing, you should set the response content type to application/json.

response.setHeader("Content-Type", "application/json");

If you're writing "pure" javascript (no framework wrapping XmlHttpRequest), you'll need to eval() the responseText to convert it to an object. If you're using something like jQuery, it will do that work for you (assuming you set the content type as suggested above).

Upvotes: 0

Raynos
Raynos

Reputation: 169391

Node.js allows you to easy manipulate HTTP request and response objects.

Ajax still sends a HTTP request object and the Ajax onsuccess callback manipulates a HTTP response object.

Writing an object to a response for an ajax request allows your ajax success handler to manipulate that data.

There are abstraction libraries for RPC like now

Upvotes: 1

Related Questions