簡體   English   中英

從JavaScript調用Perl腳本

[英]Call a Perl script from JavaScript

我想從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.html

<!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需要具有privs才能運行它。 完成所有這些檢查后,請從URL行運行腳本,以確保在嘗試從JavaScript調用腳本之前獲得某種輸出。

從JavaScript的角度來看,正如Quentin正確指出的那樣,如果您希望JavaScript代碼正確運行,還需要包括指向jQuery的鏈接。 嘗試在“正文”部分上方添加以下標題部分(並包括在內)...

<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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM