header-photo

Circumventing the AJAX cross domain policy with JSONP

I'm no expert on JSON, and I don't know the security implications of using JSONP, but I figured out how to deliver XML using this method. This seems to be the only way to pass data across domains using AJAX without using a local server side proxy to pull the data. Lets get started.

First, you'll need jQuery. That's really simple to do, just use the following:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript">
</script>

Now, the AJAX call using jQuery

<script type="text/javascript">
 $(document).ready(function(){
  jQuery.ajax({ 
   url: 'http://www.yoursite.com/yourdata.json',
   dataType: 'jsonp',
   jsonp: false,
   jsonpCallback: 'jsonpcallback'
  });
 });

 //Now, a callback

 function jsonpcallback(loadeddata) {
 //Unfortunatly, IE8 and older will not see this as XML data.
//So we have to correct it.

 if (window.ActiveXObject) {
  //for IE
  XML = new ActiveXObject("Microsoft.XMLDOM");
  XML.async="false";
  XML.loadXML(loadeddata.xml);
 } else {
  //Everythign else
   XML = loadeddata.xml;
 }
 //Do whatever you want with your data here.
}
</script>

Now, one more thing left, the JSON data

jsonpcallback({xml:'<cats><cat id="1">whatever</cat></cats>'});

I'm not 100% sure, but I believe this is set the same as a JavaScript variable. So you will need to escape all of the quote marks, and you might need to keep it on the same line.

This caused me a headache all day yesterday, but we finally reached a solution. I hope this helps anyone else using Google to figure this out.