我完全不确定我是否正确处理了这个问题。我已经在Perl中创建了一个脚本,该脚本接收一些简单的数据并创建了一个简单的json格式的输出。当我在shell中本地运行时,使用打印命令可以看到输出正确。该文件称为“ dates.cgi”,从cgi-bin目录在本地运行。当我尝试直接在本地Web服务器上访问文件时,出现500错误。当然,这不是网页,而只是json输出。
我认为这是Web服务器错误。所以我建立了一个标准的jquery ajax调用,但是它也失败了。
这是可以正确打印到终端的Perl脚本:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my $dir = '../data';
my $json;
my @dates;
opendir(DIR, $dir) or die $!;
while (my $file = readdir(DIR)) {
# Use a regular expression to ignore files beginning with a period
next if ($file =~ m/^\./);
# pluck out first 8 chars
my $temp = substr $file, 0, 8;
# populate array
push(@dates, $temp);
}
closedir(DIR);
# sort high to low
@dates = sort { $b <=> $a } @dates;
# print Dumper (@dates);
# loop through array and create inner section of json
my $len = @dates;
my $x = 0;
foreach (@dates){
if ($x < $len-1){
$json .= "\t{'date':'$_'},\n";
} else {
$json .= "\t{'date':'$_'}\n";
}
$x++;
}
# add json header and footer
$json = "{'dates':[\n" . $json;
$json .= "]}";
# print
print "$json\n";
我正在尝试以这种方式从网页访问它以将数据加载到:
// load data json
$.ajax({
url: "cgi-bin/dates.cgi",
async: false,
success: function (json) {
dates = json;
alert(dates);
alert("done");
},
fail: function () {
alert("whoops");
}
dataType: "json"
});
只是默默地失败了。我下一步要看什么?
最佳答案
您应该在perl文件中包含以下内容。
use CGI;
my $cgi = new CGI;
然后为json打印适当的标题,或者仅在打印任何内容之前使用纯文本。
print "Content-Type: application/json", "\n\n";
print "Content-type: text/plain", "\n\n";