gpt4 book ai didi

json - AJAX 无法从 Perl 正确接收 JSON 编码数据

转载 作者:行者123 更新时间:2023-12-04 20:49:34 25 4
gpt4 key购买 nike

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。

最佳答案

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

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

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

关于json - AJAX 无法从 Perl 正确接收 JSON 编码数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34602613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com