Friday, October 31, 2014

jQuery default JSON parser for AJAX calls

By default, jQuery auto detects the response format of an AJAX request and uses a predefined list of converters to use. Here's how I set the default converter when an AJAX call returns JSON data:
$.ajaxSetup({ converters: { '* text': window.String, 'text html': true, 'text json': parseDotNetJson, 'text xml': jQuery.parseXML } }); function parseDotNetJson(data) { return JSON.parse(data, function(key, value) { if (typeof value === 'string') { var a = /\/Date\((-?\d*)\)\//.exec(value); if (a) return new Date(+a[1]); } return value; }); }
I place this code in the root of a script file. I use this to convert dates parsed to JSON by ASP.Net MVC.

More info

No comments: