Skip to content

Instantly share code, notes, and snippets.

@hayajo
Last active December 25, 2015 01:39
Show Gist options
  • Save hayajo/6897275 to your computer and use it in GitHub Desktop.
Save hayajo/6897275 to your computer and use it in GitHub Desktop.
MojoliciousでJSONPの簡単なサンプル
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$( function() {
$('#hello').click(
function() {
$.ajax({
url: "http://localhost:3000/hello.js",
type: "GET",
dataType: "jsonp",
timeout: 1000,
success: function(data) {
console.log(data.hello);
$("#response").html(data.hello);
},
error: function(data) {
console.error(data);
},
complete: function(data) {
console.log("complete", data);
}
});
}
);
} );
</script>
</head>
<body>
<button id="hello">Hello</button>
<div id="response"></div>
</body>
</html>
#!/usr/bin/env perl
use Mojolicious::Lite;
get '/hello' => sub {
my $self = shift;
my $data = { hello => [qw/foo bar baz/]->[ int(rand(3)) ] };
$self->respond_to(
js => sub {
my $self = shift;
my $cb = $self->param('callback') || 'jsonp';
my $json = $self->render( json => $data, partial => 1 );
$self->render(
data => "$cb($json)",
format => 'js',
);
},
json => { json => $data },
);
};
app->start;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment