Using JSONP when returning XML

patricksweeney picture patricksweeney · Aug 8, 2010 · Viewed 18.8k times · Source

I asked an earlier question which was definitely helpful and let me know about JSONP. However, I see that I have to specify JSONP as the datatype. Now, as far as I know, that is the return type of the data coming back, which would be XML. Can XML be returned using JSONP or am I limited to it coming back as JSONP format? Thanks!

Answer

Nick Craver picture Nick Craver · Aug 8, 2010

You're limited to JSONP (and not XML) because of how it works. JSONP turns into this:

<script src="myPage?callback=myFunction" type="text/javscript">

So when you take the content, it's effectively doing this:

<script type="text/javascript">
  myFunction({ data: value, data2: value2 });
</script>

What comes back is actual running JavaScript, so it can't be XML, you'll get all sorts of syntax errors, exactly as you would doing this:

<script type="text/javascript">
  <elem>
    <data>value</data>
    <data2>value2</data2>
  </elem>
</script>

As you can imagine, the JavaScript parser isn't going to like that very much, and doesn't know what to do with it. jQuery can parse XML in most cases without any trouble, but if you're using JSONP and it's for cross-domain requests...well JSONP is your only option there, unless you wrote a proxy page on your site that didn't violate same-origin policy rules, and used it as a proxy to fetch the XML through.