开发者

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 开发者_StackOverflow社区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.?


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.


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


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
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜