Add JSON parser and exporter, to allow people to more safely parse and use JSON in their OpenLayers applications.

git-svn-id: http://svn.openlayers.org/trunk/openlayers@986 dc9f47b5-9b13-0410-9fdd-eb0c1a62fdaf
This commit is contained in:
crschmidt
2006-07-20 14:23:05 +00:00
parent 9783a64c64
commit e75ece7909

View File

@@ -1,110 +1,110 @@
/* Copyright (c) 2006 MetaCarta, Inc., published under the BSD license. /* Copyright (c) 2006 MetaCarta, Inc., published under the BSD license.
* See http://svn.openlayers.org/trunk/openlayers/license.txt for the full * See http://svn.openlayers.org/trunk/openlayers/license.txt for the full
* text of the license. */ * text of the license. */
OpenLayers.ProxyHost = "/proxy/?url="; OpenLayers.ProxyHost = "/proxy/?url=";
//OpenLayers.ProxyHost = "examples/proxy.cgi?url="; //OpenLayers.ProxyHost = "examples/proxy.cgi?url=";
/** /**
* Ajax reader for OpenLayers * Ajax reader for OpenLayers
* *
*@uri url to do remote XML http get *@uri url to do remote XML http get
*@param 'get' format params (x=y&a=b...) *@param 'get' format params (x=y&a=b...)
*@who object to handle callbacks for this request *@who object to handle callbacks for this request
*@complete the function to be called on success *@complete the function to be called on success
*@failure the function to be called on failure *@failure the function to be called on failure
* *
* example usage from a caller: * example usage from a caller:
* *
* caps: function(request) { * caps: function(request) {
* -blah- * -blah-
* }, * },
* *
* OpenLayers.loadURL(url,params,this,caps); * OpenLayers.loadURL(url,params,this,caps);
* *
* Notice the above example does not provide an error handler; a default empty * Notice the above example does not provide an error handler; a default empty
* handler is provided which merely logs the error if a failure handler is not * handler is provided which merely logs the error if a failure handler is not
* supplied * supplied
* *
*/ */
/** /**
* @param {} request * @param {} request
*/ */
OpenLayers.nullHandler = function(request) { OpenLayers.nullHandler = function(request) {
alert("Unhandled request return " + request.statusText); alert("Unhandled request return " + request.statusText);
}; };
/** Background load a document /** Background load a document
* *
* @param {String} uri URI of source doc * @param {String} uri URI of source doc
* @param {String} params Params on get (doesnt seem to work) * @param {String} params Params on get (doesnt seem to work)
* @param {Object} caller object which gets callbacks * @param {Object} caller object which gets callbacks
* @param {Function} onComplete callback for success * @param {Function} onComplete callback for success
* @param {Function} onFailure callback for failure * @param {Function} onFailure callback for failure
* *
* Both callbacks optional (though silly) * Both callbacks optional (though silly)
*/ */
OpenLayers.loadURL = function(uri, params, caller, OpenLayers.loadURL = function(uri, params, caller,
onComplete, onFailure) { onComplete, onFailure) {
if (OpenLayers.ProxyHost && uri.startsWith("http")) { if (OpenLayers.ProxyHost && uri.startsWith("http")) {
uri = OpenLayers.ProxyHost + escape(uri); uri = OpenLayers.ProxyHost + escape(uri);
} }
var success = (onComplete) ? onComplete.bind(caller) var success = (onComplete) ? onComplete.bind(caller)
: OpenLayers.nullHandler; : OpenLayers.nullHandler;
var failure = (onFailure) ? onFailure.bind(caller) var failure = (onFailure) ? onFailure.bind(caller)
: OpenLayers.nullHandler; : OpenLayers.nullHandler;
// from prototype.js // from prototype.js
new Ajax.Request(uri, new Ajax.Request(uri,
{ method: 'get', { method: 'get',
parameters: params, parameters: params,
onComplete: success, onComplete: success,
onFailure: failure onFailure: failure
} }
); );
}; };
/** Parse XML into a doc structure /** Parse XML into a doc structure
* @param {String} text * @param {String} text
* *
* @returns Parsed Ajax Response ?? * @returns Parsed Ajax Response ??
* @type ? * @type ?
*/ */
OpenLayers.parseXMLString = function(text) { OpenLayers.parseXMLString = function(text) {
//MS sucks, if the server is bad it dies //MS sucks, if the server is bad it dies
var index = text.indexOf('<'); var index = text.indexOf('<');
if (index > 0) { if (index > 0) {
text = text.substring(index); text = text.substring(index);
} }
var ajaxResponse = Try.these( var ajaxResponse = Try.these(
function() { function() {
var xmldom = new ActiveXObject('Microsoft.XMLDOM'); var xmldom = new ActiveXObject('Microsoft.XMLDOM');
xmldom.loadXML(text); xmldom.loadXML(text);
return xmldom; return xmldom;
}, },
function() { function() {
return new DOMParser().parseFromString(text, 'text/xml'); return new DOMParser().parseFromString(text, 'text/xml');
}, },
function() { function() {
var req = new XMLHttpRequest(); var req = new XMLHttpRequest();
req.open("GET", "data:" + "text/xml" + req.open("GET", "data:" + "text/xml" +
";charset=utf-8," + encodeURIComponent(text), false); ";charset=utf-8," + encodeURIComponent(text), false);
if (req.overrideMimeType) { if (req.overrideMimeType) {
req.overrideMimeType("text/xml"); req.overrideMimeType("text/xml");
} }
req.send(null); req.send(null);
return req.responseXML; return req.responseXML;
} }
); );
return ajaxResponse; return ajaxResponse;
}; };
/** Adds a new script element to the head of the current document, /** Adds a new script element to the head of the current document,
@@ -117,4 +117,105 @@ OpenLayers.addScript = function(url) {
var scriptElem = document.createElement("script"); var scriptElem = document.createElement("script");
scriptElem.src = url; scriptElem.src = url;
head.appendChild(scriptElem); head.appendChild(scriptElem);
}; };
(function () {
var m = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
s = {
array: function (x) {
var a = ['['], b, f, i, l = x.length, v;
for (i = 0; i < l; i += 1) {
v = x[i];
f = s[typeof v];
if (f) {
v = f(v);
if (typeof v == 'string') {
if (b) {
a[a.length] = ',';
}
a[a.length] = v;
b = true;
}
}
}
a[a.length] = ']';
return a.join('');
},
'boolean': function (x) {
return String(x);
},
'null': function (x) {
return "null";
},
number: function (x) {
return isFinite(x) ? String(x) : 'null';
},
object: function (x) {
if (x) {
if (x instanceof Array) {
return s.array(x);
}
var a = ['{'], b, f, i, v;
for (i in x) {
v = x[i];
f = s[typeof v];
if (f) {
v = f(v);
if (typeof v == 'string') {
if (b) {
a[a.length] = ',';
}
a.push(s.string(i), ':', v);
b = true;
}
}
}
a[a.length] = '}';
return a.join('');
}
return 'null';
},
string: function (x) {
if (/["\\\x00-\x1f]/.test(x)) {
x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
var c = m[b];
if (c) {
return c;
}
c = b.charCodeAt();
return '\\u00' +
Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
});
}
return '"' + x + '"';
}
};
Object.prototype.toJSONString = function () {
return s.object(this);
};
Array.prototype.toJSONString = function () {
return s.array(this);
};
})();
String.prototype.parseJSON = function () {
try {
return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
this.replace(/"(\\.|[^"\\])*"/g, ''))) &&
eval('(' + this + ')');
} catch (e) {
return false;
}
};