Using jQuery with JSONP, a brief example


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;

When run, the output looks like this:

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

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

This script is called “”. 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:

    <script type="text/javascript" src=""></script>
    <script type="text/javascript">
      $(document).ready(function () {
                function (d) {
                  alert("got: " +;

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.