Mojolicious::Plugin::JSONP - Render JSONP with transparent fallback to JSON
plugin JSONP => callback => 'callback_function'; get '/' => sub { shift->render_jsonp({one => 'two'}); }; # GET request: # ?callback_function=my_function # Response: # my_function({"one":"two"})
Mojolicious::Plugin::JSONP is a helper for rendering JSONP with a transparent fallback to JSON if a callback parameter is not specified.
The render_jsonp helper renders a Perl reference as JSON, wrapped in a supplied callback. If a callback is not supplied, only the JSON structure is returned.
Given the following configuration:
plugin JSONP => callback => 'callback_function';
And the following action:
get '/' { shift->render_jsonp({one => 'two'}) };
And this client (browser) request:
http://domain.com/?callback_function=my_function
The following is returned:
my_function({"one":"two"});
If the client request does not specify the expected callback function:
http://domain.com/ # No parameters specified
Only the JSON is returned:
{"one":"two"}
Optionally, specify the callback function name in the render_jsonp helper:
get '/' => sub { shift->render_jsonp(callback_function => {one => "two"}); };
Overriding plugin configuration, the following response is returned:
callback_function({"one":"two"})
Mojolicious::Plugin::JSONP inherits all methods from Mojolicious::Plugin and implements the following new ones.
register
$plugin->register(Mojolicious->new);
Register plugin in Mojolicious application.
Mojolicious, Mojolicious::Guides, http://mojolicio.us.
To install Mojolicious::Plugin::JSONP, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Mojolicious::Plugin::JSONP
CPAN shell
perl -MCPAN -e shell install Mojolicious::Plugin::JSONP
For more information on module installation, please visit the detailed CPAN module installation guide.