通过AJAX调用Perl Script来打印文本文件的内容

Calling Perl Script through AJAX to print the contents of a text file

本文关键字:文件 文本 打印 AJAX 调用 Perl Script 通过      更新时间:2023-09-26

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

我有我的文件在htdocs,我的服务器访问这些文件。当我单击test.html时,它弹出一个按钮"test",并成功地调用perl脚本,简单地打印出一条消息。也就是说,perl脚本只是打印"helloworld",HTML文件"提醒"用户,即当按钮被按下时打印出"helloworld"。这很好。

问题是,我想做的是调用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中。这里的问题是什么?

我怀疑Perl脚本的当前工作目录与htdocs不同。你应该用它的路径来完全限定文件名。

:

  • 对于每个 Perl程序

  • 你应该总是 use strictuse warnings
  • 如前所述,#!行必须是文件

  • 中的第一行
  • 当你告诉客户端下面的数据是HTML时,它是简单的文本

  • 对于词法文件句柄,应该使用open的三个参数for

你的程序的更新考虑到这些点

#!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;