views:

310

answers:

4
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.?

+4  A: 

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.

Pointy
Thanks, but actually I'm more concerned that jQuery.param isn't serializing ANYTHING for Date objects, but encodeURIComponent knows Date()'s just fine. In this case, the format isn't really problematic because my (Rails) server can parse all reasonable date formats, including plain 'ol .toString() as you suggest.
A: 

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()) + ")\/"
Oleg
A: 

I think this is a jQuery bug in the following context:

  • jQuery 1.4.2 (1.3.2 works)
  • new methods added into Date.prototype
Dragos Rusea
A: 

if date is in format "/Date(8978947479238)/"

i m using jquery datatables and when i pass my date object to it, it shows date as "/Date(8978947479238)/"... i want to convert it into proper format like yy-mm-dd....

Any Help???????????

Muhammad Jhanzeb