[cgiapp] Ajax and JSON recipe

Michael Peters mpeters at plusthree.com
Thu Apr 9 13:37:09 EDT 2009


Lyle Brooks wrote:

> Does anyone have a short starter example of code (both server and client)
> that they would be willing to post/share that would show Ajax/JSON 
> usage with CGI::Application?

The client is just Javascript and it's best to pick a framework to handle all 
the messy browser details for you. I use Prototype, but I like JQuery as well. 
The details of how to use them depend on the framework, so I won't put those 
examples in here. And then for the backend, using CGI::Application::Plugin::JSON 
makes it really easy.

Also, there are several ways to JSON in your application. You can just return 
full JSON structures as the body of their reply.

   return $self->json_body({ foo => 1, bar => 2});

Sometimes it's nice to return HTML in the body but with some extra information 
in your HTTP headers as JSON:

   $self->json_header({ valid => 1 });
   return $html_tmpl->output;

And then there is JSONP (http://en.wikipedia.org/wiki/JSON#JSONP) which is 
basically returning Javascript that executes over some JSON. Really nice and 
simple for mashups, etc.

-- 
Michael Peters
Plus Three, LP



More information about the cgiapp mailing list