I have defined an ajax dataFilter for my jQuery calls that return JSON data to ensure that .Net-encoded dates are automatically converted to JavaScript dates on return:
$.ajaxSetup({
dataFilter: function(data, type) {
var rx = /"\\\/Date\(([0-9]+)\)\\\/"/g;
if(type == 'json' && typeof(data) == 'string' && rx.test(data)) {
var obj = JSON && JSON.parse ? JSON.parse(data) : eval(data);
replaceMicrosoftJSONDates(obj);
return obj;
}
return data;
}
});
The replaceMicrosoftJSONDates function works fine; it recursively iterates through the object and replaces strings matching the appropriate date format string with actual JavaScript dates, but here it is for testing purposes:
function replaceMicrosoftJSONDates(obj) {
for(var p in obj)
switch(typeof(obj[p])) {
case 'string':
var match = /^\/Date\(([0-9]+)\)\/$/.exec(obj[p]);
if(match) obj[p] = new Date(parseInt(match[1]));
break;
case 'object':
replaceMicrosoftJSONDates(obj[p]);
break;
}
}
The problem is with the dataFilter function. If I return the modified JSON object, null is sent as the data parameter to the ajax success callback:
$.ajax({
type: 'GET',
cache: false,
url: __appPath + 'path/to/my/page',
success: function(data) {
console.log(data); // displays null
}
});
As far as I can tell, the jQuery private function involved in this process is ajaxConvert, which you can see at https://github.com/jquery/jquery/blob/master/src/ajax.js#L897-979
Keep in mind the following:
- This is not a cross-domain scripting call
- The server is return an HTTP200 (OK) response and the responseText has the full data
- The data is being sent correctly to the dataFilter function
- The dataFilter function appears to correctly parsing and modifying the response and returning a valid JavaScript object, already parsed and ready to consume
If I return a string from the dataFilter function, jQuery does its job correctly and sends me a parsed JSON object. If I return a pre-parsed JavaScript object, jQuery sends null to my success callback. I am using jQuery 1.5.2 in this case and this filter used to work in other applications and older versions of jQuery. Now all of a sudden it doesn’t seem to work anymore.
SOLUTION
Here: http://forum.jquery.com/topic/datafilter-function-and-json-string-result-problems
Rick Strahl had problem similiar to this recently (this seems to be specific for jQuery 1.5.2). As I don’t wan’t to copy his work, here is his solution which should easly guide you to solve your problem: http://codepaste.net/i89xhc