Using Perl Variable Values In JavaScript of Web Page Generated with Perl
Is that headline a mouthful or what :)
We intermittently receive queries about how to use Perl variables within JavaScript. This would be JavaScript that's part of a web page generated/created by the Perl script.
Here is an example:
#!/usr/bin/perl use strict; my $elapsed = (localtime())[7]; print "Content-type: text/html\n\n"; print <<PAGE; <html> <body> <h1>Testing</h1> <script type="text/javascript" language="JavaScript"><!-- document.write('<p>$elapsed days have passed this year.</p>'); var numberOfDays = $elapsed + 1; document.write('<p>This is day number ' + numberOfDays + '.</p>'); //--></script> <h1>Done testing</h1> </body> </html> PAGE # end of file
In the above code, the Perl script will replace every instance of "$elapsed" with the number assigned to it near the top of the file.
It's simple and clear once it's explained. Prior to knowing how it's done, it can be baffling.
Will Bontrager