【发布时间】:2013-05-09 09:42:27
【问题描述】:
我正在做一个使用 jQuery、AJAX、JSON 和 Perl 的小项目。在后端,我使用 Perl 及其 CGI 模块返回 JSON ojbect。
#!/usr/software/bin/perl5.8.8
use strict;
use warnings;
use CGI qw(:standard);
use JSON;
print header('application/json');
my $json;
# eventually the json that will be returned will based on params,
# for now using this list as example.
$json->{"entries"} = [qw(green blue yellow red pink)];
my $json_text = to_json($json);
print $json_text;
在How can I send a JSON response from a Perl CGI program?的帮助下,我能够编写上述脚本
这个脚本是使用 jQuery 的 get 调用的:
jQuery.getJSON("script.pl?something=whatever", function(data, status) {
console.log(data);
console.log(status);
},"json").error(function(jqXhr, textStatus, error) {
/* I am always ending up here. */
console.log(jqXhr);
console.log("ERROR: " + textStatus + ", " + error);
});
从上面的 jQuery 调用中,我期望得到一个 JSON 对象,但我得到了整个 Perl 脚本。我知道我的内容类型设置正确,因为当我从命令行执行脚本时我得到了这个:
Content-Type: application/json
谁能帮我解决这个问题。谢谢。
【问题讨论】:
-
这是您的 Web 服务器的配置问题。它需要配置为将 Perl 脚本作为 CGI 运行。你用的是什么服务器?
-
作为建议,您应该首先通过直接从浏览器访问 URL 来测试 JSON 服务,然后再在 AJAX 调用中使用它们。这样生活(或至少调试)更简单:)