0

So, I have a basic HTML page using jQuery 1.6.2 and I have an MVC application that serves data on a separate domain (The HTML page is local, the MVC application is not). The MVC application is sending back a JSON string just fine; the problem is that when sending back dates, there are a "/" before and after the date which breaks the JSON string, which in turn does not get turned into a javascript object. Phew.

Here is my AJAX call:

$.ajax({ 
  url:url,
  dataType: 'jsonp',
  success: function(data, status, jqXHR) {
    alert(data);
  },
  error: function(jqXHR, textStatus, errorThrown) {
    console.log(jqXHR); console.log(textStatus); console.log(errorThrown);
  }
});

Using the "network" tab in the Chrome profiler, I can see that a JSON string is being returned, and it has the correct data, but has some malformed syntax. Here is a sample of that:

"DateAuthorized":"\/Date(1307789505000-0500)\/",

I tried to use dataType "text", but because this is a cross-domain request, I have to use jsonp.

Any ideas what-so-ever? Can the MVC application use a regex to remove the slashes? Is there a way to use javascript XHttpRequest to build a manual request?

Agh!

1 Answer 1

4

It's using the default serializer which is the JavaScriptSerializer which has always had this issue. An alternative is to use JSON.NET to serialize your objects.

You can always implement a replacement from the client-side -- parseJSON extension

...Or format it from the server-side like this before sending it back:

return new DateTime(2012, 4, 19).ToLongDateString(); // or ToShortDateString()
6
  • I'm not at work still, but as soon as I get in tomorrow morning I will try extending the function. Thanks! Apr 19, 2012 at 22:56
  • Does $.ajax call $.parseJSON on a successful response header? Apr 20, 2012 at 16:17
  • Yes, you call $.parseJSON once you've received the JSON data. Apr 20, 2012 at 18:10
  • I meant that the $.ajax call must perform some kind of validation on the string before it converts it to an object, right?. I don't think I can do anything client-side, so I'll have to go through the right channels to get the application updated. Thanks for your help! Apr 20, 2012 at 18:31
  • 1
    $.ajax doesn't do anything to JSON. The $.parseJSON extension extends the regular deserializer from JSON to object. I highly recommend moving your conversions on the server-side though. Apr 20, 2012 at 18:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.