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

标签 javascript json perl

我根本不确定我是否正确地处理了这个问题。我在 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/

相关文章:

javascript - Angular 5无法读取未定义的属性 'target'

javascript - 如何确认该代码段已在 Node.js 中完成执行

javascript - 将嵌套对象与 JavaScript 中的数组进行比较并返回键相等

json - 下载后如何打印自定义 JSON 对象值?

java - 如何在Java中流畅地解析和遍历JSON对象

perl - Perl 中的 CPU/内核数

perl - 使用 Perl Ansi 颜色为整个屏幕着色

javascript - 为什么这些 console.log 语句不起作用? Electron

javascript - 使用打印按钮在浏览器中将字节数组显示为 PDF?

html - 我如何开始使用 Perl 进行 Web 开发?