Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

[OT] Syntax for: AJAX Prototype JSON response

by graq (Curate)
on Feb 19, 2007 at 12:16 UTC ( #600822=perlquestion: print w/ replies, xml ) Need Help??
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 )=-

Comment on [OT] Syntax for: AJAX Prototype JSON response
Select or Download Code
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 )=-

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://600822]
Approved by jettero
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (14)
As of 2014-12-19 08:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (74 votes), past polls