我正在做一个使用jQuery,AJAX,JSON和Perl的小项目。在后端,我使用Perl和它的CGI模块来返回一个JSON ojbect。为什么我无法从Perl脚本返回json对象?
#!/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运行。你使用什么服务器? – friedo
作为建议,您应该首先通过直接从浏览器访问URL来测试JSON服务,然后才能在AJAX调用中使用它们。生活(或至少调试)更简单:) – DVK