2015-11-05 53 views
0

我想使用JavaScript POST JSON并使用Perl脚本读取POST结果。我已经编写了这段代码,但无法让Perl脚本读取JSON文本。如何通过JavaScript发送JSON并在Perl中解码它?

HTML:

<!DOCTYPE html> 
<html> 
<head> 
<title>Testing ajax</title> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
<script> 
var d = { 
    "name": "Bob", 
    "sex": "Male", 
    "address": { 
     "city": "San Jose", 
     "state": "California" 
    }, 
    "friends": [ 
     { 
      "name": "Alice", 
      "age": "20" 
     }, 
     { 
      "name": "Laura", 
      "age": "23" 
     }, 
     { 
      "name": "Daniel", 
      "age": "30" 
     } 
    ] 
}; 

$(document).ready(function() { 
    $("#test").click(function() { 
     $.ajax({ 
      type: 'POST', 
      url: '/cgi-bin/Raghav_test/Apollo/read_ajax3.pl', 
      data: "r=" + d, 
      success: function(res) { alert("data" + res); }, 
      error: function() { alert("did not work"); } 
     }); 
    }); 
}); 
</script> 
</head> 
<body> 
<button id="test">Testing</button> 
</body> 
</html> 

的Perl:

#!/usr/bin/perl -w 

use CGI; 
#use DBD; 
use DBI; 
use JSON::PP; 
use Data::Dumper; 
use DBD::Oracle qw(:ora_types); 
use lib "/var/www/cgi-bin/ICE_LIBRARY/"; 

require '/var/www/cgi-bin/import_scripts/library/common_lib.pl'; 
require "/var/www/cgi-bin/import_scripts/library/script_log.pl"; 

use database_conf; 
my $db = new database_conf; 

#my $EP_dev_conn = $db->db_eportal_dev; 
my $EP_prod_conn = $db->db_eportal_prod; 
my $cgi = CGI->new; 
my $id = $cgi->param("r"); 
#my $data = $cgi->param('POSTDATA'); 

print "Content-type:text/html\n\n"; 

#my $value = $ddata->{'address'}{'city'} ; 
# Here I'd like to receive data from jQuery via ajax. 
#my $id = $cgi->param('apiKey'); 
#$json = qq{{"ID" : "$id"}}; 
#my $method = $cgi->param('method'); 
#my $ip = $cgi->param('ip'); 

$json = qq{"$id"}; 
print $json; 
exit; 
+1

你需要调用'JSON.stringify()'你把请求的对象上,然后你需要的JSON字符串在Perl代码进行解码。 –

+2

此外,你应该编辑你的文章,以包括你看到的输出,而不仅仅是说,基本上,“它不工作”。 –

+0

我的答案解决了你的问题吗? –

回答

1

您需要发出请求之前调用你的对象JSON.stringify()

$.ajax({ 
    type: 'POST', 
    url: '/cgi-bin/Raghav_test/Apollo/read_ajax3.pl', 
    data: { "r": JSON.stringify(d) }, 
    success: function(res) { alert("data" + res); }, 
    error: function() { alert("did not work"); } 
}); 

然后你需要调用decode_json()上要解析它并将其转换为Perl数据结构的字符串:

my $q = CGI->new; 
my $json = $q->param("r"); 
my $href = decode_json($json); 

print Dumper($href); 

输出:

$VAR1 = { 
      'address' => { 
         'state' => 'California', 
         'city' => 'San Jose' 
         }, 
      'name' => 'Bob', 
      'friends' => [ 
         { 
          'name' => 'Alice', 
          'age' => '20' 
         }, 
         { 
          'age' => '23', 
          'name' => 'Laura' 
         }, 
         { 
          'name' => 'Daniel', 
          'age' => '30' 
         } 
         ], 
      'sex' => 'Male' 
     };