sammy
sammy

Reputation: 223

JSON from Perl to Javascript

I am sending a JSON object from my Perl Program to a Javascript jQuery code segment. While I have been doing this for years in PHP, something is not working. My Perl Code does this:

@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;

Now my javaScript/jquery segment is:

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

The first alert shows the following:

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

But the second alert show cards to be of length 0. The array was not assigned to cards. The double quotes are not added by the Perl code. It must be a by-product of JSON being shipped through the CGI gateway.

When I run a standalone Javascript scenario, it works.

But not when passed through CGI.

Thanks for any help.

Upvotes: 0

Views: 242

Answers (1)

Miller
Miller

Reputation: 35198

Check out: 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);

Upvotes: 3

Related Questions