Skip to content

Instantly share code, notes, and snippets.

@beppu
Created August 26, 2009 02:48
Show Gist options
  • Select an option

  • Save beppu/175265 to your computer and use it in GitHub Desktop.

Select an option

Save beppu/175265 to your computer and use it in GitHub Desktop.
package JSONP;
use strict;
use warnings;
use base 'Squatting';
# How to send JSONP responses with Squatting
# ==========================================
#
# save this as JSONP.pm
# run it by typing: squatting JSONP
# go to a site that uses jQuery like http://www.reddit.com/
# open FireBug and go to the Javascript console
# type: jQuery.ajax({ url: 'http://localhost:4234/', dataType: 'jsonp', success: function(data){ console.log(data) } })
#
# The JSONP response from this app should be printed to FireBug's console if all went well.
package JSONP::Controllers;
use Squatting ':controllers';
our @C = (
C(
Home => [ '/' ],
get => sub {
my ($self) = @_;
$self->v->{callback} = $self->input->{callback};
$self->v->{data} = { foo => rand(999), bar => 2 };
$self->render('_');
},
)
);
package JSONP::Views;
use Squatting ':views';
use JSON;
my $json = JSON->new;
our @V = (
V(
'jsonp',
_ => sub {
my ($self, $v) = @_;
my $js = '(' . $json->encode($v->{data}) . ')';
if ($v->{callback}) {
$js = "$v->{callback}$js";
}
$js;
}
)
);
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment