如何通过ajax向Perl脚本发送数据?

4
我希望通过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;

2
检查服务器访问和错误日志文件。 - mpapec
非常感谢您的评论。那么,这是否意味着"$cgi = CGI->new; and $id = $cgi->param('data_id');"在jQuery中接收数据不是错误的? - Akio Yanagawa
6
(1) 请在您的Perl脚本中添加use strict; use warnings以声明变量。(2) 据我所见,您实际上没有print $cgi->header(...)(3) 要查看您的脚本收到了什么参数,请将参数转储到日志文件中:use Data::Dumper; print STDERR Dumper $cgi->Vars(4) 要对JSON进行解码或编码,请使用use JSON模块。 - amon
非常感谢您的编辑和建议。我会修改代码并尝试它。 - Akio Yanagawa
2个回答

9

不确定您是否已经解决了这个问题,但也许其他人会遇到这个问题并想知道它是如何工作的。

请查看下面的代码。如果您想运行此代码,请将index.html文件复制到您的html目录中(例如/var/www/html),将perl脚本复制到您的cgi-bin目录中(例如/var/www/cgi-bin)。请务必使perl脚本可执行!在我的代码中,cgi目录位于/cgi-bin/ajax/stackCGI - 请相应更改。

我还添加了一个稍微高级一点的示例,介绍如何使用Perl cgi、AJAX和JSON:点击,另外还有一个示例,介绍如何通过AJAX使用JSON从Javascript传递数组到Perl:点击

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

我认为你忘记打印标题了:

$cgi->header(-type => "application/json", -charset => "utf-8");

应该是

print $cgi->header(-type => "application/json", -charset => "utf-8");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接