Using jQuery with JSONP, a brief example

Posted: by Joe Johnston

Since I couldn’t find a jquery/jsonp example that I liked, here is my stab at it.

JSONP is a way of getting around cross-domain restrictions browsers levy on javascript HTTP calls. The protocol makes the server return a JS code fragement of a function that it then executes. Sneaking, right?

Imagine a server with this bit of perl CGI code:

#!/usr/local/bin/perl --
use strict;
use CGI;

sub main {
  my $q = CGI->new;
  my $callback = $q->param('callback') || 'foo';

  my $data = q[{id:0, name:'jjohn'}];
  my $ret = qq[$callback ($data);];

  print $q->header("-content-type" => "text/javascript"), $ret;
}
main();

When run, the output looks like this:

Content-Type: text/javascript; charset=ISO-8859-1

foo ({id:0, name:'jjohn'});

This script is called “ws.pl”. It is smart enough to call use a different function name if one is requested by the client.

On the client/JS side, you can use this data this way:

<html>
  <head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function () {
         $.getJSON('http://games.taskboy.com/ws.pl?callback=?',
                function (d) {
                  alert("got: " + d.name);
                });     
       });
    </script>
  </head>
</html>

Here, an alert box will appear. Notice that the callback function producing the alert has received the decoded JSON object and is able to use it directly. No need to worry about injecting SCRIPT tags, etc.

jQuery takes the huge pain of javascript programming out of javascript programming.