开发者

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 = {..开发者_如何学JAVA.};
  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!


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


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜