2013-05-14 94 views
0

我正在做一个使用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 

有人可以帮我想出解决办法。谢谢。

+2

这是您的Web服务器的配置问题。它需要配置为将您的Perl脚本作为CGI运行。你使用什么服务器? – friedo

+0

作为建议,您应该首先通过直接从浏览器访问URL来测试JSON服务,然后才能在AJAX调用中使用它们。生活(或至少调试)更简单:) – DVK

回答

4

,而不是我得到整个Perl脚本

服务器未运行Perl脚本,它是服务于它为纯文本。

您需要阅读服务器的手册以了解如何为CGI配置它。

0

正如其他人指出的那样,您需要配置您的Web服务器以运行perl脚本作为CGI。如果你的Web服务器是Apache和你的CGI被命名为“json.cgi”,那么你会喜欢这一行添加到您的httpd.conf:

AddHandler的CGI脚本的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”为故事的其余部分。

相关问题