Skip to content

Instantly share code, notes, and snippets.

@dvinciguerra
Created August 24, 2012 17:09
Show Gist options
  • Save dvinciguerra/3452989 to your computer and use it in GitHub Desktop.
Save dvinciguerra/3452989 to your computer and use it in GitHub Desktop.
Mojolicious::Lite and Ajax Example
#!/usr/bin/env perl
use DateTime;
use Mojolicious::Lite;
get '/' => 'index';
get '/service/datetime' => sub {
my $self = shift;
my $dt = DateTime->now;
my $date = $dt->dmy('/');
my $hour = $dt->hour;
my $min = $dt->minute;
$self->render_json({ datetime => "$date $hour:$min" });
};
app->start;
__DATA__
@@ index.html.ep
% layout 'default';
<p id="clock"></p>
@@ layouts/default.html.ep
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>Mojolicious::Lite Ajax Exemple</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<%= content %>
<script type="text/javascript">
$(function(){
setInterval(function(){
$.ajax({
type:'GET',
url:'/service/datetime',
dataType: 'json',
success: function(json){
$('#clock').html( json.datetime );
}
});
}, 500);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment