[英]Why can't I return a json object from a Perl script?
我正在做一个使用jQuery,AJAX,JSON和Perl的小项目。 在后端,我正在使用Perl及其CGI模块返回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;
在“ 如何从Perl CGI程序发送JSON响应”的帮助下,我能够编写上述脚本。
使用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
有人可以帮我解决这个问题吗? 谢谢。
相反,我得到了整个Perl脚本
服务器未运行Perl脚本,而是将其作为纯文本提供。
您需要阅读服务器手册,以了解如何为CGI配置它。
正如其他人指出的那样,您需要配置Web服务器以将perl脚本作为CGI运行。 如果您的Web服务器是Apache,并且您的CGI名为“ json.cgi”,那么您需要在httpd.conf中添加如下一行:
AddHandler cgi-script .cgi
由于您使用的是jQuery,因此您应该从JSON窗格中的to_json标题下阅读这个小块:
If you want to write a modern perl code which communicates to outer
world, you should use "encode_json" (supposed that JSON data are
encoded in UTF-8).
对于其余的故事,请使用“ perldoc JSON” 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.