rplantiko

A simple JSONP wrapper with Perl

Oct 26th, 2015 (edited)
578
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.54 KB | None | 0 0
  1. #!"\xampp\perl\bin\perl.exe"
  2. #
  3. #  jsonp.pl
  4. #
  5. #  Reads a json file and wraps it in a JavaScript function call
  6. #  One reason to do this is for better decoupling: A JSON file on the server contains the data
  7. #  But the Javascript function to be applied on it belongs to the Web UI (i.e. to the HTML/CSS/JS layer)
  8. #
  9. #  With the HTML element
  10. #    <script src="status.js?jsonp=show_status"></script>
  11. #  the server will send back: "show_status( <content of status.js> );"
  12. #
  13. #  Thus, the UI-specific function show_status will immediately be executed on receive
  14. #
  15. #  Combine this with an internal redirection of query strings in your server
  16. #  In Apache, you may write in your .htaccess
  17. #
  18. #     RewriteEngine on                                                          
  19. #     RewriteCond %{QUERY_STRING}     jsonp=([^&]*)                       [NC]  
  20. #     RewriteRule ^(.*)$              /cgi-bin/jsonp.pl?file=$1&jsonp=%1  [PT,L]
  21. #
  22.  
  23. use strict;
  24. use warnings;
  25.  
  26. my %args = ();
  27. foreach (split /&/, $ENV{QUERY_STRING}) {
  28.   my ($name,$value) = split /=/;
  29.   $args{$name} = $value;
  30.   }
  31.  
  32. print "Content-type: text/javascript; charset=utf-8\n\n";
  33.  
  34. if (not exists $args{file}) {
  35.   print "Error: No JSON file given in URL path\n";
  36.   exit;
  37. }
  38.  
  39. if (not exists $args{jsonp}) {
  40.   print "Error: No 'jsonp' parameter specified\n";
  41.   exit;
  42. }  
  43.  
  44. open( my $JSON,"<$ENV{DOCUMENT_ROOT}/$args{file}");
  45. if (not $JSON) {
  46.   print "Can't open '$args{file}': $!";
  47.   exit;
  48. }
  49.  
  50. print "$args{jsonp}(\n";
  51. foreach (<$JSON>) {
  52.   print;
  53. }
  54. print "\n);";
  55.  
  56. close $JSON;
Add Comment
Please, Sign In to add comment