Agile Ajax

101 Ideas for JSONP - Idea #2: Wrap XML in JSONP

Sometimes you have some Javascript code, either something you've already written or a third-party library (like this XSLT library) that wants and expects XML. You don't want to rewrite the whole thing, so it would be nice to be able to adapt these without doing a whole lot of work. Once you realize that you can process an XML document from a string, not just a file loaded using XHR...

JSONPIdeas.parseXML = function(xmltext) {
var doc;
// code for IE
if (window.ActiveXObject)
{
doc=new ActiveXObject("Microsoft.XMLDOM");
doc.async="false";
doc.loadXML(xmltext);
}
// code for Mozilla, Firefox, Opera, etc.
else
{
var parser=new DOMParser();
doc=parser.parseFromString(xmltext,"text/xml");
}
return doc;
}

...the solution is obvious -- just wrap the XML as a string inside a JSON object.

The approach to doing this is even simpler than for our previous example. We simply proxy the web service and escape double quotes, backslashes, newlines and carriage returns and wrap it in a JSON object:

public String getJSONWrap(String uri) {
String xmlResult = getXML(uri);
// escape the double quotes and backslashes
String replace1 = xmlResult.replaceAll("\\\\", "\\\\\\\\");
replace1 = replace1.replaceAll("\\n", "\\\\n");
replace1 = replace1.replaceAll("\\r", "\\\\r");
String replaced = replace1.replaceAll("\"", "\\\\\"");
// wrap it in a JSON object
return "{\"Result\":\"" + replaced + "\"}";
}

I've wrapped this web service -- http://www.trynt.com/ip-data-api/v1/ -- that returns ARIN information. The box below should show you your hostname and the country you are connecting from. The Javascript code that makes it go can be found here. (Note that some of the ARIN data isn't always valid XML and the service above doesn't actually deal with it, so occasionally you'll have XML parse errors, but that would be the case whether or not you used JSONP or not.)

The first two ideas are really the basics of everything else we will do using JSONP. Next time, a little fun with XQuery.



Technorati : , ,

Topics:

Leave a comment

Powered by WP Hashcash

About Pathfinder

  • We design and build extraordinary applications for companies looking to make the next great idea a reality.
  • learn more

Topics

WordPress

Comments about this site: info@pathf.com