Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
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
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 )=-

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 wandering the Monastery: (12)
As of 2015-07-30 15:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (272 votes), past polls