Include JavaScript in Perl-CGI generated page

2019-08-27 12:36发布

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 ?

3条回答
Fickle 薄情
2楼-- · 2019-08-27 13:16

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.

查看更多
趁早两清
3楼-- · 2019-08-27 13:18

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 $.)

查看更多
我只想做你的唯一
4楼-- · 2019-08-27 13:36

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

查看更多
登录 后发表回答