AJAX没有从Perl正确接收JSON编码数据

时间:2016-01-05 00:57:54

标签: json ajax perl

Perl结果已正确编码为JSON,响应头已设置为“application / json”,AJAX配置似乎没问题。或者我错过了吗?

use strict;
use warnings;
use Cwd;
use JSON::PP qw(encode_json);
use CGI qw(:standard);


chdir( cwd() . "/gallery" );

my $cdir = cwd();
my @win = split ( ' ', `ls $cdir` );

my $res = [ ''.scalar(@win) ]; 

foreach my $w ( @win )
{
    open ( my $fp, "<:utf8", "$cdir/$w/tag.txt" );
    while( <$fp> )
    {
        unless( m#^\s*$# )
        {
            chomp;
            push ( @$res, $_ );
        }
    }
    close ($fp);
}

my $resInJSON = encode_json($res);


print "Content-type: application/json\n\n";
print $resInJSON;    

终端输出:

Content-type: application/json

["2","2015-1-2 cat","2015-1-4 dog and girl"]

Javascript代码是:

function loadGallery()
{
    $.ajax(
    {
     type: 'GET',
     url: "/cgi-bin/count.cgi", 
     async: false,
     dataType: 'json',
     success: function(result)
        {
            document.getElementById("test-output-1").innerHTML = result[0];   // output is 3
            document.getElementById("test-output-2").innerHTML = result[1];   // output is undefined
            document.getElementById("test-output-3").innerHTML = result[2];   // output is undefined
        }
    });
} loadGallery();

AJAX接收dataType已经是JSON。

2 个答案:

答案 0 :(得分:0)

我相信您正试图将result[0]result[0][0]="2"result[0][1]="2015-1-2 cat"切换为result[0][2]="2015-1-4 dog and girl"

答案 1 :(得分:0)

你没有提供可运行的演示。当我使它可运行时,它会产生预期的结果。

zzz.html

<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>

<div id="test-output-1"></div>
<div id="test-output-2"></div>
<div id="test-output-3"></div>

<script>
function loadGallery()
{
    $.ajax(
    {
     type: 'GET',
     url: "zzz.cgi",
     async: false,
     dataType: 'json',
     success: function(result)
        {
            document.getElementById("test-output-1").innerHTML = result[0];
            document.getElementById("test-output-2").innerHTML = result[1];
            document.getElementById("test-output-3").innerHTML = result[2];
        }
    });
}

loadGallery();
</script>

zzz.cgi

#!/usr/bin/perl
use strict;
use warnings;
print "Content-type: application/json\n\n";
print q{["2","2015-1-2 cat","2015-1-4 dog and girl"]};

输出:

2
2015-1-2 cat
2015-1-4 dog and girl

看起来JSON调用的脚本返回

[["2","2015-1-2 cat","2015-1-4 dog and girl"]]

代替

["2","2015-1-2 cat","2015-1-4 dog and girl"]

也许您没有调用您认为正在调用的脚本?或者您可能从早期版本的脚本获得缓存响应?