Transferring javascript variables from client to server
I am programming a strange script that consists开发者_高级运维 of transferring variables from client to a nodejs server.
So if a have a date variable, how can I transfer it and use the same variable on the server?Is there any way to serialize objects and retrieve them on server side in a way that they remain the same type (date, function, variable, string, object...)? Thank youYou can serialize a date by converting it to a number which can be sent via JSON.
new Date(+new Date)
is perfectly valid.
The prefix +
in
+new Date
converts the newly created date to a number, and
new Date(myNumber)
reconstitutes a date from a number.
You might check out DNode in addition to nowjs. I've been watching both of those projects but not dabbled in them yet. However, I get the sense that DNode it is building more traction in the node.js community and I hear praise for it all the time.
https://github.com/substack/dnode http://substack.net/posts/85e1bd/DNode-Asynchronous-Remote-Method-Invocation-for-Node-js-and-the-Browser
Timezones are very important in my application, so I've found that serializing dates to ISO8601 formatted strings for dates works best. @Mike's solution is great if you don't care about timezones, or can assume that all dates are UTC. There are plenty of javascript libraries to help serialize/deserialize ISO8601.
Now.js could abstract all of the serialisation, deserialisation.. it provides a shared namespace between node.js server and browser client:
http://nowjs.com/
As was posted before me, serialize the Date Object
to a string literal, either the value in miliseconds or the formatted Date
String.
Use a POST request passing the Date
string in the request body or a GET requests passing the string via query parameter to get it to the server. There you may deserialize the string using the Date
constructor.
精彩评论