从JavaScript调用Perl脚本

Call a Perl script from JavaScript

本文关键字:脚本 Perl 调用 JavaScript      更新时间:2023-09-26

我想从JavaScript调用Perl脚本。Perl脚本将文件从一个文件夹移动/复制到另一个文件夹。但是当我尝试调用它时,它没有运行。

我是这个领域的新手,所以一点帮助对我来说意义重大。

copy_file.pl

#!/usr/bin/env perl
use strict;
use warnings;
use File::Copy;
my $source_dir = "/home/Desktop/file";
my $target_dir = "/home/Desktop/Perl_script";
opendir(my $DIR, $source_dir) || die "can't opendir $source_dir: $!";  
my @files = readdir($DIR);
foreach my $t (@files) {
  if (-f "$source_dir/$t" ) {
    # Check with -f only for files (no directories)
    copy "$source_dir/$t", "$target_dir/$t";
  }
}
closedir($DIR);

home。

<!DOCTYPE html>
<html>
  <body>
    <h1>My First JavaScript</h1>
    <p>Click Date to display current day, date, and time.</p>
    <button type="button" onclick="myFunction()">Date</button>
    <p id="demo"></p>
    <script>
      function myFunction() {
        document.getElementById("demo").innerHTML = Date();
        $.get("copy_file.pl");
      }
    </script>
  </body>
</html> 

这看起来像是CGI/Apache的问题。要使Perl代码在Apache环境中正确运行,您需要返回一个Content Type头,作为代码输出的第一个内容之一。尝试使用看起来更像这样的代码…

#!/usr/bin/env perl
use strict;
use warnings;
print "Content-Type: text/html'n'n";
use File::Copy;
use CGI::Carp qw(fatalsToBrowser); #nice error handling, assuming there's no major syntax issues that prevent the script from running
my $source_dir = "/home/Desktop/file";
my $target_dir = "/home/Desktop/Perl_script";
opendir(my $DIR, $source_dir) || die "can't opendir $source_dir: $!";  
my @files = readdir($DIR);
foreach my $t (@files) {
  if (-f "$source_dir/$t" ) {
    # Check with -f only for files (no directories)
    copy "$source_dir/$t", "$target_dir/$t";
  }
}
closedir($DIR);
print "<h1>OK</h1>'n";
print "<p>Print</p>'n";
__END__

此外,不用说,您需要确保脚本在文件系统上也需要被标记为可执行,并且Apache需要具有运行它的权限。检查完所有这些后,从URL行运行脚本,以确保在尝试从JavaScript调用脚本之前获得某种输出。

从JavaScript的角度来看,如果想让JavaScript代码正常工作,还需要包含一个指向jQuery的链接,正如Quentin正确指出的那样。尝试在Body部分上方添加以下header部分(和include)…

<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>

如果你查看你的JavaScript错误控制台,你会看到它在抱怨$没有定义。

你似乎在尝试使用jQuery,你需要在你的页面中包含它的库,然后才能使用它提供的功能。

<script src="path/to/where/you/put/jquery.js"></script>