gpt4 book ai didi

javascript - 如何使用 Perl 和 Javascript 创建和访问 json 文件

转载 作者:行者123 更新时间:2023-12-03 11:02:14 26 4
gpt4 key购买 nike

我根本不确定我是否正确地处理了这个问题。我在 Perl 中创建了一个脚本,它接受一些简单的数据并创建一个简单的 json 格式的输出。当我在 shell 中本地运行它时,我可以使用打印命令看到输出是正确的。该文件名为“dates.cgi”,并从 cgi-bin 目录本地运行。当我尝试直接在本地 Web 服务器上访问该文件时,收到 500 错误。当然,这不是网页,只是 json 输出。

我认为这是一个网络服务器错误。所以我设置了一个标准的 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 header ,或者在打印任何内容之前仅使用纯文本。

print "Content-Type: application/json", "\n\n";

print "Content-type: text/plain", "\n\n";

关于javascript - 如何使用 Perl 和 Javascript 创建和访问 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28031964/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com