繁体   English   中英

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

[英]AJAX doesn't receive JSON encoded data correctly from 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。

我相信你试图切割result[0]所以result[0][0]="2"result[0][1]="2015-1-2 cat"result[0][2]="2015-1-4 dog and girl"

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

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"]

也许你没有打电话给你认为你打电话的剧本? 或者您可能从早期版本的脚本获得缓存响应?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM