Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get JSONP-like fetching of XML in jQuery?

For a web service I'm developing I would like my embedded code (on the client's site) to fetch an XML file from my sever script which resides on my domain.

As this is a cross-domain request I figured to use JSONP as it seems the de facto standard for such APIs. However, for my application it would be easier for me to use XML instead of JSON. Now, I could of course convert my XML to JSON on the server and then back again to XML in the client's site JavaScript, but that seems unnecessarily cumbersome. What I really need is and XMLP solution, XML with padding.

I tired googling but couldn't find a solution that does that. Does anyone know a simple solution?

like image 397
odedbd Avatar asked Apr 19 '10 21:04

odedbd


3 Answers

You could use something like Yahoo! Query Language (YQL) to save you from having to write another output format for your XML file.

For example to get the XML feed for this question via JSONP-X you would use a YQL query URL like:

http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D%27http%3A%2F%2Fstackoverflow.com%2Ffeeds%2Fquestion%2F2671143%27%20and%20itemPath%3D%27feed.entry%27&callback=my_jsonpx_handler

[Try this query in the YQL console]

Which gives you a result like the following; effectively the XML wrapped in a JSON callback:

my_jsonpx_handler({"query":…,"results":["<entry xmlns=\"http://www.w3.org/2005/Atom\">\n <id>http://stackoverflow.com/questions/2671143/is-there-an-existing-tool-for-jsonp-like-fetching-of-xml-in-jquery<\/id>\n <re:rank xmlns:re=\"http://purl.org/atompub/rank/1.0\" scheme=\"http://stackoverflow.com\">0<\/re:rank>…"]});

Your widgets could then query the YQL URL for their data which in turn will talk to the XML file on your server (with caching, speed, etc. as added goodies).

like image 68
salathe Avatar answered Oct 22 '22 22:10

salathe


The only reason json works is because included javascript on your page can run in the window without any x-domain issues. So it must remain javascript. However, you could just minify the xml, make sure it's properly escaped and send it as a value in a json object.

echo 'callback({data: "' + xml string + '"});';

Or something along those lines.

like image 42
Alex Sexton Avatar answered Oct 22 '22 22:10

Alex Sexton


As of jQuery 1.5 there is a utility method, it's saved my life for using jsonp to load in XML.

var xml = "<rss version='2.0'><channel><title>RSS Title</title></channel></rss>",
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$title = $xml.find( "title" );

http://api.jquery.com/jQuery.parseXML/

like image 1
Paul Cooper Avatar answered Oct 22 '22 20:10

Paul Cooper