Code_Snippet

Thursday Tech Tip – AJAX Cross Domain

At work I do a lot of prototyping against API services that come from both internal and external sources. If you are on a Mac and testing locally a web page that leverages API calls from the client side in the Safari browser, there are no issues there. It is when you want to host these files and share your demo that issues arise. I am not a command line jockey, so configuring test boxes for server-side REST calls is not something I like to spend a ton of time on. So, I often have to rely on a Cross Domain Scripting hack or two for my client-side calls to work.

Generally the best ways for using API calls on the client-side are to use JSONP (JSON with Padding) or have the service update their headers to be CORS compliant, if you have access to this. Absent either of these options you can often be stranded for a solution. This week I discovered a clever script fromĀ Bart Van der Donck that helps you make client-side API calls by leveraging a Perl script that gets called as a JavaScript file and handles the request for you. Below you will see a simple example of how the script is leveraged in your markup.

<script src="http://www.ajax-cross-domain.com/cgi-bin/ACD/ACD.js?uri=(http://www.google.com)"></script><script>// <![CDATA[
alert(ACD.responseText);
// ]]></script>

The code above alerts the source code of www.google.com. You can test it here. Using the ACD.js file does require some server-side hackery but if you can get through that, it will make rapid prototyping of API mash-ups and demos easier. One other caveat to Bart’s script is that it doesn’t allow you to easily submit dynamic APIP request easily and you will have to create some workarounds there. Again, ideally, everyone should support and be using either JSONP or CORS, until then, this script is a welcome workaround.

Leave a Reply