Perl結果已正確編碼爲JSON並且響應標頭已設置爲「application/json」,AJAX配置似乎沒有問題。或者我錯過了什麼?從終端AJAX無法從Perl正確接收JSON編碼的數據
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。
'console.log(result)'告訴你什麼? –
@Matt雅各布什麼都沒有顯示!? –
「AJAX無法正確接收JSON編碼的數據」 - 您如何確定?它收到了什麼?開發人員工具中的「網絡」選項卡顯示的請求是什麼? – Quentin