Jean
Jean

Reputation: 22745

Include JavaScript in Perl-CGI generated page

I was trying to add a java-script to a page which is generated on the fly. I tried this, but it seems like it is not working.

<SCRIPT SRC=\"sorttable.js\"></SCRIPT>

I always have to inline javacode along with the html for it to work. Any clues ?

Upvotes: 0

Views: 9178

Answers (3)

Yue Ma
Yue Ma

Reputation: 31

Perhaps this link might be helpful: http://perlmeme.org/tutorials/cgi_form.html

It provides method of embedding a jsp function into the form-onsubmit as follow:

print $q->start_form( -name => 'main_form', -method => 'GET', -enctype => &CGI::URL_ENCODED,

  -onsubmit => 'return javascript:validation_function()',
  -action => '/where/your/form/gets/sent',   );

And there is a following link from Perl5 CGI library - support for Javascript, it's about linking javascript function to an event. http://cpansearch.perl.org/src/MARKSTOS/CGI.pm-3.60/cgi_docs.html#javascripting

Regards

Upvotes: 2

Leolo
Leolo

Reputation: 1337

qq() is the equivalent of "", but with matching delimiters. It is going to be your friend if you are outputing HTML or JavaScript.

print qq(<script type="text/javascript">alert("The world is my oyster");</script>);

Note that you don't have to use () as delimiters, see perlop.

If you are outputting JavaScript that is building HTML, you should be using jQuery or Ext. But either way you will be in the multiple-levels-of-escaping-hell. JSON::XS might make your life less painful. Also learn about here-documents:

my $js = <<'JS';
    alert( 'The world is my oyster' );
    var $href = "example.html";
    document.write( '<a href="' + $href + '">clicky</a>' );
JS
print qq(<script type="text/javascript">$js</script>);

The tricky bit about the above is that $href is a JavaScript variable, not a Perl variable. (Yes, JS identifiers may include $.)

Upvotes: 4

Axeman
Axeman

Reputation: 29854

Well it depends on your quoting structure for the WHOLE thing. If you're printing this out in a uninterpolated heredoc, then \" just creates a bigger problem.

   print <<'END_HTML';
   ...
      <SCRIPT SRC=\"sorttable.js\"></SCRIPT>
   ...
   END_HTML

or a q expression:

  print q~
   ...
      <SCRIPT SRC=\"sorttable.js\"></SCRIPT>
   ...
   ~;

So you would have to show more of your context. But let me assure you: when I write out the tags the right way, my JavaScript files gets sourced into the page, just as I would expect.

Upvotes: 1

Related Questions