2014-03-27 28 views
0

我從我的Perl程序發送一個JSON對象到一個Javascript jQuery代碼段。 雖然我一直在PHP這樣做了很多年,但有些東西不起作用。 我的Perl代碼做到這一點:JSON從Perl到Javascript

@cards=(1,2,3,4,5); 
@repairs=(6,7,8,9,10); 
my $json->{"cards"} = \@cards; 
$json->{"repairs"} = \@repairs; 
print "Content-type: text/html", "\n\n"; 
my $json_text = to_json($json); 
print $json_text; 

現在我的JavaScript/jQuery的部分是:

$.post(perl_program_name, 
    { 
    card_code:card_code, 
    }, 
    function(object) { 
    alert('alerting'+object); 
    var cards=new Array; 
    var cards=object.cards; 
    alert(cards); 
    ... 

第一個警報顯示如下:

{"cards":["1","2","3","4","5"], 
"repairs":["6","7","8","9","10"] 
} 

但第二警報顯示卡長度爲0.陣列未分配給卡片。 雙引號不會被Perl代碼添加。它必須是通過CGI網關發貨的JSON的副產品。

當我運行一個獨立的Javascript方案,它的工作原理。

但是不通過CGI時。

感謝您的任何幫助。

回答

3

退房:What is the correct JSON content type?

use strict; 
use warnings; 

use JSON; 

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

my $json = { 
    cards => [1..5], 
    repairs => [6..10], 
}; 

print to_json($json); 
+0

萬分感謝。這是罪魁禍首。 – sammy