Alex Rivera | Logout

How can I send a JSON response from a Perl CGI program?

Asked 2009-01-12T13:48:10.117
20

I am writing a JSON response from a perl/cgi program. The header's content type needs to be "application/json". But it doesn't seems to be recognized as response is thrown as a text file.

I would be capturing response using JSON library of jQuery. Where am I missing in sending the JSON response.

Edit
Report

1 Answer

1

Here is how to generate the request in Mason, the web framework for Perl.

Mason is analogous to Pylons or Ruby On Rails.

<%init>

use JSON;

my %hash = { a => 'a', b => 'b' };
my @list = ( 1, 2, \%hash );

# Mason object $r for Apache requests, automatically sets the header
$r->content_type('application/json');

# Pass a reference to anything (list, hash, scalar) for JSON to encode
my $json = new JSON;
print $json->encode(\@list);

</%init>

And then handle it in Prototype, the JavaScript web abstration:

var req = new Ajax.Request('request.html', {
    method: 'get',
    parameters: {
        whatever: 'whatever'
    },
    onCreate: function() {
        // Whatever
    },
    onSuccess: function(response) {
        // This only works if you set the 'application/json' header properly
        var json = response.responseJSON;

        // Since you sent a list as the top-level thing in the JSON,
        // then iterate through each item
        json.each(function(item) {
            if (item instanceof Object) {
                item = new Hash(item);
            } else if (item instanceof Array) {
                // Do array stuff
            } else {
                // Do scalar stuff
            }
        });
    },
    onFailure: function() {
        // Failed
    }
});
answered 2010-01-21T17:18:17.890

Your Answer