NAME
Catalyst::View::JSON - JSON view for your data
SYNOPSIS
# lib/MyApp/View/JSON.pm
package MyApp::View::JSON;
use base qw( Catalyst::View::JSON );
1;
# configure in lib/MyApp.pm
MyApp->config({
...
'V::JSON' => {
allow_callback => 1, # defaults to 0
callback_param => 'cb', # defaults to 'callback'
expose_stash => [ qw(foo bar) ], # defaults to everything
},
});
sub hello : Local {
my($self, $c) = @_;
$c->stash->{message} = 'Hello World!';
$c->forward('MyApp::View::JSON');
}
DESCRIPTION
Catalyst::View::JSON is a Catalyst View handler that returns stash data in JSON format.
CONFIG VARIABLES
- allow_callback
-
Flag to allow callbacks by adding
callback=function
. Defaults to 0 (doesn't allow callbacks). See "CALLBACKS" for details. - callback_param
-
Name of URI parameter to specify JSON callback function name. Defaults to
callback
. Only effective whenallow_callback
is turned on. - expose_stash
-
List or regular expression object, to specify which stash keys are exposed as a JSON response. Defaults to everything. Examples:
# only exposes keys 'foo' and 'bar' expose_stash => [ qw( foo bar ) ], # only exposes keys that matches with /^json_/ expose_stash => qr/^json_/,
CALLBACKS
By default it returns raw JSON data so your JavaScript app can deal with using XMLHttpRequest calls. Adding callbacks to the API gives more flexibility to the end users of the API: overcome the cross-domain restrictions of XMLHttpRequest. It can be done by appending script node with dynamic DOM manipulation, and associate callback handler to the returned data.
For example, suppose you have the following code.
sub end : Private {
my($self, $c) = @_;
if ($c->req->param('output') eq 'json') {
$c->forward('MyApp::View::JSON');
} else {
...
}
}
/foo/bar?output=json
will just return the data set in $c->stash
as JSON format, like:
{ result: "foo", message: "Hello" }
but /foo/bar?output=json&callback=handle_result
will give you:
handle_result({ result: "foo", message: "Hello" });
and you can write a custom handle_result
function to handle the returned data asynchronously.
The valid characters you can use in the callback function are
[a-zA-Z0-9\.\_\[\]]
but you can customize the behaviour by overriding the validate_callback_param
method in your View::JSON class.
See Yahoo's nice explanation on http://developer.yahoo.net/common/json.html
AUTHOR
Tatsuhiko Miyagawa <miyagawa@bulknews.net>
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.