4

I want to send data to Perl script via ajax, and to receive a json format back from it. But it doesn't work. I know something is wrong in the following scripts. Does anyone know how to fix it?

jQuery code:

$("#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 script):

#!/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;
4

2 回答 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 的更高级的示例:click以及另一个关于如何使用 JSON 通过 AJAX 将数组从 Javascript 传递到 Perl 的示例:click

索引.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;
于 2015-03-11T17:09:21.630 回答
1

我想,你忘了打印标题:

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

应该

print $cgi->header(-type => "application/json", -charset => "utf-8");
于 2015-03-12T11:28:07.900 回答