Include JavaScript in Perl-CGI generated page

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-25 16:54:09

问题


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 ?


回答1:


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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/4108607/include-javascript-in-perl-cgi-generated-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!