2016-01-05 50 views
3

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。

+0

'console.log(result)'告訴你什麼? –

+0

@Matt雅各布什麼都沒有顯示!? –

+0

「AJAX無法正確接收JSON編碼的數據」 - 您如何確定?它收到了什麼?開發人員工具中的「網絡」選項卡顯示的請求是什麼? – Quentin

回答

0

我相信你試圖切片result[0]所以result[0][0]="2",result[0][1]="2015-1-2 cat"result[0][2]="2015-1-4 dog and girl"

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

也許你不叫你以爲你是調用腳本?或者,也許你正在從早期版本的腳本獲得緩存響應?