Dojo Javascript Ajax Date JSON Fix

by cjgaudin

JavaScript

/*
Example of Usage
dojo.xhrGet({
url: "/Item/Load/1",
handleAs: "aspjson",
load: function(result) { // result is a JS object with dates set to JS Dates from asp.net
// Do something with the result here
}
});
*/
(function (dojo) {
    // JSON RegExp
    var rvalidchars = /^[\],:{}\s]*$/;
    var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
    var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
    var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
    var dateISO = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:[.,]\d+)?Z/i;
    var dateNet = /\/Date\((\d+)(?:-\d+)?\)\//i;

    // replacer RegExp
    var replaceISO = /"(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:[.,](\d+))?Z"/i;
    var replaceNet = /"\\\/Date\((\d+)(?:-\d+)?\)\\\/"/i;

    // determine JSON native support
    var nativeJSON = (window.JSON && window.JSON.parse) ? true : false;
    var extendedJSON = nativeJSON && window.JSON.parse('{"x":9}', function (k, v) { return "Y"; }) === "Y";

    var jsonDateConverter = function (key, value) {
        if (typeof (value) === "string") {
            if (dateISO.test(value)) {
                return new Date(value);
            }
            if (dateNet.test(value)) {
                return new Date(parseInt(dateNet.exec(value)[1], 10));
            }
        }
        return value;
    };

    dojo.contentHandlers.aspjson = function (xhr) {
        var data = xhr.responseText
        if (typeof data !== "string" || !data) {
            return null;
        }
        data = $.trim(data);
        // Make sure the incoming data is actual JSON
        // Logic borrowed from http://json.org/json2.js
        //var r = _d.fromJson(data || null);
        if (rvalidchars.test(data
                .replace(rvalidescape, "@")
                .replace(rvalidtokens, "]")
                .replace(rvalidbraces, ""))) {
            // Try to use the native JSON parser
            if (extendedJSON || (nativeJSON)) {
                return...