我想通过ajax将数据发送到Perl脚本,并从中接收json格式。但它不起作用。我知道以下脚本中有问题。有谁知道如何解决它?
jQuery代码:
$("#test").click(function(){
var ID = 100;
var data = {
data_id : ID
};
$.ajax({
type: "POST",
url: "ajax.cgi",
data: data,
success: function(msg){
window.alert(msg);
}
});
});
ajax.cgi(perl脚本):
#!/usr/bin/perl
use CGI;
use DBI;
$cgi = CGI->new;
# Here I'd like to receive data from jQuery via ajax.
$id = $cgi->param('data_id');
$json = qq{{"ID" : "$id"}};
$cgi->header(-type => "application/json", -charset => "utf-8");
print $json;
exit;
答案 0 :(得分:8)
不确定你现在是否已经解决了这个问题,但也许其他人偶然发现了这个问题,并想知道它是如何运作的。
请找到以下代码。如果要运行此代码,只需将index.html文件复制到html目录(例如/ var / www / html),将perl脚本复制到cgi-bin目录(例如/ var / www / cgi-bin)。确保使perl脚本可执行!在下面的代码中,cgi目录位于/ cgi-bin / ajax / stackCGI中 - 请相应更改。
我还添加了一个稍微更高级的示例,介绍如何使用Perl cgi,AJAX和JSON:click以及另外一个关于如何使用JSON通过AJAX将数组从Javascript传递到Perl的示例:{{3 }}
的index.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>
$(document).ready(function() {
$("#test").click(function(){
var ID = 100;
$.ajax({
type: 'POST',
url: '/cgi-bin/ajax/stackCGI/ajax.pl',
data: { 'data_id': ID },
success: function(res) {
alert("your ID is: " + res.result);
},
error: function() {alert("did not work");}
});
})
})
</script>
</head>
<body>
<button id="test" >Testing</button>
</body>
</html>
ajax.pl
#!/usr/bin/perl
use strict;
use warnings;
use JSON; #if not already installed, just run "cpan JSON"
use CGI;
my $cgi = CGI->new;
print $cgi->header('application/json;charset=UTF-8');
my $id = $cgi->param('data_id');
#convert data to JSON
my $op = JSON -> new -> utf8 -> pretty(1);
my $json = $op -> encode({
result => $id
});
print $json;
答案 1 :(得分:1)
我想,你忘了打印标题:
$cgi->header(-type => "application/json", -charset => "utf-8");
应该是
print $cgi->header(-type => "application/json", -charset => "utf-8");