Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.param() - doesn't serialize javascript Date objects?

jQuery.param({foo: 1});             // => "foo=1" - SUCCESS!
jQuery.param({bar: new Date()});    // => "" - OUCH!

There is no problem with encodeURIComponent(new Date()), which is what I would have thought param is calling for each member.

Also, explicitly using "traditional" param (e.g. jQuery.param(xxx, true)) DOES serialize the date, but alas, that isn't of much help since my data structure isn't flat.

Is this because typeof(Date) == "object" and param tries to descend into it to find scalar values?

How might one realistically serialize an object that happens to have Date's in it for $.post() etc.?

like image 214
user336234 Avatar asked May 08 '10 15:05

user336234


2 Answers

You're probably going to want the date transformed into a string, since that's what it's going to have to be on the wire anyway.

$.param({bar: new Date().toString()});

Now you may want it formatted in some particular way so that your server gets something it can parse. I think that the datejs library has support for formatting, or you could roll your own by picking out pieces of the date with getDate(), getMonth(), getYear() etc.

like image 54
Pointy Avatar answered Sep 21 '22 07:09

Pointy


If you work with Microsoft products on the server side you should take in consideration, that Microsoft serialize Date as a number of milliseconds since UTC, so as a number. To be more exact, the serialization string look like /Date(utcDate)/, where utcDate date is this number. Because JSON supports the backslash as an escape character you should use code like following to serialize a Date object myDate:

"\/Date(" +  Date.UTC(myDate.getUTCFullYear(), myDate.getUTCMonth(),
                      myDate.getUTCDate(), myDate.getUTCHours(),
                      myDate.getUTCMinutes(), myDate.getUTCSeconds(),
                      myDate.getUTCMilliseconds()) + ")\/"
like image 35
Oleg Avatar answered Sep 23 '22 07:09

Oleg