Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

[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.

<script language="javascript" type="text/javascript" src="prototype.js +"></script> <script> function ajax_test() { new Ajax.Request('/cgi-bin/', { 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
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).


    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?

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

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (1)
As of 2015-11-27 04:33 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (718 votes), past polls