http://qs321.pair.com?node_id=600822

graq has asked for the wisdom of the Perl Monks concerning the following question:

I'm looking for the correct return syntax (for a JSON object) to hand back to my Prototype AJAX httpRequest.

The HTML:
<script language="javascript" type="text/javascript" src="prototype.js +"></script> <script> function ajax_test() { new Ajax.Request('/cgi-bin/ajax.pl', { method:'get', onSuccess: function(transport, json){ alert(json ? Object.inspect(json) : "no JSON object"); }, onFailure: function(){ alert('Something went wrong...') } }); } </script> <a href="#" onClick="javascript:ajax_test();">TEST</a>
The script:
#!/usr/bin/perl use strict; use warnings; use JSON; my %hash = ( foo => 'bar', 1 => 2, this => 'that', ); my $js = objToJson(\%hash); print "Content-type: text/javascript\n\n"; print $js

-=( Graq )=-

Replies are listed 'Best First'.
Re: [OT] Syntax for: AJAX Prototype JSON response
by derby (Abbot) on Feb 19, 2007 at 13:13 UTC

    I use a content type of "application/json" and I normally use the header methods provided by CGI or CGI::Application rather than hand coding. If you want the onFailure to trigger, you'll need to set the appropriate http status (4xx, 5xx).

    -derby

    update: and by 'normally', I mean by following rfc 4627.

Re: [OT] Syntax for: AJAX Prototype JSON response
by graq (Curate) on Feb 19, 2007 at 16:33 UTC
    For completeness, here is the slight syntax change needed to the original perl code:
    ... print "Content-type: text/javascript\n"; print "X-JSON:$js\n\n";

    However, it has been pointed out that IE doesn't like large headers, so it is probably best to return the JSON object in the response body and eval it for oneself.

    -=( Graq )=-