1

我正在使用 AJAX 和基于 Web 的服务器 [APACHE] 来调用 perl 脚本。

我在 htdocs 中有我的文件,我的服务器可以在其中访问这些文件。当我单击 test.html 时,它会弹出一个按钮“test”并成功调用 perl 脚本来简单地打印出一条消息。即 perl 脚本只打印“helloworld”,而 html 文件“警告”用户,即当按下按钮时打印出“hello world”。这工作正常。

问题是,我想做的是调用 perl 脚本“check.pl”,其中 check.pl 打开一个文本文件“simple.txt”,将该文本文件的内容存储在一个字符串中,然后打印结果. 因此,通过按下 test.html 生成的按钮,它应该打印出文本文件的内容。现在 simple.txt 只是一句话。

这是我的 HTML,它成功执行了一个 perl 文件 [check.pl]:


<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {

//create a variable that will reference the XMLHttpRequest we will create
var xmlhttp;


//****Want it compatible with all browsers*****
//try to create the object in microsoft and non-microsoft browsers
if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
} else {
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

//set the event to be a function that executes
xmlhttp.onreadystatechange=function() {
    var a;
    //when server is ready, go ahead
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    //get number from text file, add one to it and output 
    //the original number and the resulting number.
    a = xmlhttp.responseText;
    alert(a);
    }
}
//execute perl script
xmlhttp.open("GET","check.pl",false);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<Apache2.2>/<check.pl>?fileName=<simple.txt>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>

这是它调用的 perl 脚本:


#test to see if we can open file and print its contents

#The following two lines are necessary!
#!C:\indigoampp\perl-5.12.1\bin\perl.exe
print "Content-type: text/html\n\n";

#This line allows the entire file to be read not just the first paragraph.
local $/;

#Open file that contains the source text to work with
open(FILESOURCE, "simple.txt") or die("Unable to open requested file: simple.txt :$!");

#Store the whole text from the file into a string
my $document = <FILESOURCE>;
print $document;
close (FILESOURCE);

我是 perl、AJAX、HTML 和 javascript 的新手。问题是当我按下按钮时,什么也没有出现。事实上,“simple.txt”的内容应该提醒用户。我查看了错误日志文件,它说“无法打开 simple.txt,文件或目录不存在”。不过,正如我之前所说,我的所有三个文件都在 htdocs 中。这里可能是什么问题?

4

1 回答 1

1

我怀疑您的 Perl 脚本的当前工作目录不同于htdocs. 您应该使用其路径完全限定文件名。

还:

  • 对于每个Perl 程序,您应该始终 use strictuse warnings

  • 如前所述,该#!行必须是文件中的第一行

  • 当它是简单文本时,您告诉客户端以下数据是 HTML。

  • 您应该将三参数 foropen与词法文件句柄一起使用。

您的程序的此更新考虑了这些要点

#!C:\indigoampp\perl-5.12.1\bin\perl.exe

use strict;
use warnings;

my $filename = 'simple.txt';

open my $source, '<', 'C:\path\to\htdocs\\'.$filename
        or die qq{Unable to open requested file "$filename": $!};

my @document = <$source>;
print "Content-type: text/plain\n\n";
print @document;
于 2013-04-28T20:28:19.763 回答