Reputation: 15811
I'm writing a jQuery app that interfaces with a node.js server, so I'd like to pass JSON around everywhere.
It seems like jQuery's $.post(url, data, ...)
method sends its data in URL-encoded form. i.e, {foo: true, bar: "baz"}
becomes foo=true&bar=baz
, losing data type information.
Can I get jQuery to send the data in JSON format? Or should I just call $.post
with a pre-JSON.stringify
'd string?
Upvotes: 0
Views: 1234
Reputation:
I believe that using $.post may be your best bet. However, if you are working with Node.js and are building a very JavaScript intensive application, I'd recommend you checkout Now.js for RPC calls between your Node.js server and the client-side code.
There is a great example of creating a chat application using Now.js and Node.js. However, I'm not sure how the internals of Now.js are implemented if you are very concerned about performance client-side.
Update
Here is the link to the Now.js homepage: http://nowjs.com. Using this framework let's your client-side and server side work very closely together and seamlessly.
Upvotes: 0
Reputation:
The short answer is that jQuery won't do it for you. Pulled from the jQuery soure:
// convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
basically if the data isn't a string coming in, jQuery is going to parse it into one just like you're seeing. So if you want it to be JSON going to the server, you're going to have to do it yourself. I'd suggest not using JSON.stringify since it's not cross-browser. Here's my "toJSON" function if you're interested: https://gist.github.com/884348
You could always mess with $.ajax if you want. I've done it a fair bit.
Upvotes: 1