views:

194

answers:

2

Hi,
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 jquery plug-in that does that. Anyone knows a simple solution?

+3  A: 

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.

Alex Sexton
Thanks! This seems like just the kind of simple solution I was hoping for. I haven't tried it yet, but except for the escaping part, I fail to foresee any difficulty.
BearCode
+3  A: 

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\"&gt;\n <id>http://stackoverflow.com/questions/2671143/is-there-an-existing-tool-for-jsonp-like-fetching-of-xml-in-jquery&lt;\/id&gt;\n <re:rank xmlns:re=\"http://purl.org/atompub/rank/1.0\" scheme=\"http://stackoverflow.com\"&gt;0&lt;\/re:rank&gt;…"]});

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).

salathe
Very useful, thanks for bringing this to my attention
gnarf
Thanks for the detailed and helpful suggestion. Alex's suggestion seems a little simpler though, which I like a lot.
BearCode