我遇到了挫折,我用 javascript 制作了一个 Html 页面,并且我使用 AJAX 调用 Perl 函数。问题是,当我的 Perl 程序不需要参数时,调用就很简单了。但我有一个打开和读取文件的函数,因此我需要将文件的位置提供给 perl 脚本,因此必须通过 AJAX 调用中的参数传递它。 前工作电话:
function getOption(){
var selectmenu=document.getElementById("Select1")
selectmenu.onchange=function(){ //run some code when "onchange" event fires
var chosenoption=this.options[this.selectedIndex] //this refers to "selectmenu"
if (chosenoption.value!="nothing"){
var s = chosenoption.text;
openFile("C:\PerlTest\test.txt");
}
}
}
前。尝试传递参数时不起作用:
function openFile(name){
XMLHttp.open("GET", "/cgi-bin/readFile.pl"+name, true);
XMLHttp.onreadystatechange = function() {
if (XMLHttp.readyState == 4) {
document.getElementById("TxtArea").innerHTML = XMLHttp.responseText;
}
}
XMLHttp.send(null);
}
由于这个示例,我尝试以这种方式传递参数:
http://www.suite101.com/content/how-to-create-a-simple-perl-ajax-application-a136201
谁能帮忙吗?
非常感谢。
经过 Kinopiko 的建议,这是有道理的,我有以下内容:
HTML-
function openFile(name){
XMLHttp.open("GET", "/cgi-bin/readFile.pl?file="+encodeURI(name), true);
XMLHttp.onreadystatechange = function() {
if (XMLHttp.readyState == 4) {
var container = XMLHttp.responseText.split("\n");
if (container.length>0){
for ( i=0; i< container.length-1;i++){
document.getElementById("TxtArea").innerHTML += container[i] + " ";
}
}
}
else{
document.getElementById("TxtArea").innerHTML = "333";//XMLHttp.responseText;
}
}
XMLHttp.send(null);
}
Perl 脚本:
#!c:/Perl/bin/perl
use strict;
use CGI qw/param/;
use URI::Escape;
print "Content-type: text/html\n\n";
my $file = param ('file');
$file = uri_unescape ($file);
open (MYFILE, $file);
while (<MYFILE>) {
chomp;
print "$_\n";
}
close (MYFILE);
现在我在 javascript 中没有收到错误,但我的 XMLHttp.readyState 从来都不是 4,所以我没有获取文件的内容。
也许我使用的encodeURI错误??
谢谢。
最佳答案
首先需要添加一个问号:
XMLHttp.open("GET", "/cgi-bin/readFile.pl?file="+name, true);
您还需要使用 encodeURI
对“name”进行百分比编码。
在Perl端,你可以使用像CGI这样的模块来获取文件的值:
use CGI qw/param/;
my $file = param ('file');
然后
use URI::Escape;
$file = uri_unescape ($file);
关于javascript - 使用 AJAX 在 HTML 中调用 Perl 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4488822/