Cross Domain Ajax Approaches

Recently I've been working on a very fun project: Radio Widget, which allows me to code while enjoying all kinds of music provided by RadioTime API. The project is strongly attached to the browser. By that means when doing CORS , I have to face scope issues. For example, on Google Chrome, I need to make an Ajax call from chrome:// scope, as well as my server scope http://. That's the primary reason I come up with this article to summarize Cross Domain Ajax Approaches.


Normally, when you want to make a cross domain call at front-end, jQuery will do the work.

  type: "GET",
  url: "",
  dataType: "jsonp"

But this approach requires that remote server has JSONP data available or provides Web service API . If not, then we need server support, which goes to next approach:

2) Proxy

A proxy can be written in any server-side language. Basically your script makes a call to your server. Your server makes the call to the remote server. Parse the data from remote server, e.g. wrap result data into JSON format, and then return it back to Client.

For example, you can use PHP CURL to write a proxy. Here is an awesome demonstration from Ben Alman(Cowboy).

3) Apache mod_rewrite

This is a very handy technique especially you are working on your local machine. It basically utilizes Apache rewrite rule to achieve the same goal. Here is an example:

RewriteEngine On
RewriteRule    ^/proxy/(.*)   http://$1    [L,P]

Say you want to call Google at your server:

Behind the scene, it does this

4) Something else

If you expect a simple response like success or fail, e.g. Check if the server is on/off, you can approach this by simply creating an img tag and setting the src of the image:

var img  = new Image(), 
    ping = function(options, callback) {
        img.onload = function() {
            if (callback)
        img.onerror = function() {
        img.src = "";

Yang Zhao

Read more posts by this author.