How To Pass A Variable Value From Javascript To Perl
Solution 1:
On the JavaScript side you will need to send a GET request to the Perl script. I've only done this using jQuery (see docs) so you'll need to adapt this if you want a pure JavaScript solution:
functiongetUserIp(ips) {
var ipString = ips.join(';');
$.ajax({
type: 'GET',
url: '/path/to/script.pl',
data: { user_ips : ipString },
statusCode: {
200: function(data, textStatus, jqXHR) {
$('#id').html(jqXHR.responseText);
}
}
});
}
Note that the ips
variable should be a string when you pass it to Perl. You can pass an array of params to Perl (see CGI docs), but I've found splitting a string after the fact to be the most reliable.
I'll show how to capture the parameter using Perl CGI because its simple, but if you're planning on making a full website then I strongly recommend using a web framework. There are several for Perl, like Catalyst and Mojolicious, with varying learning curves.
Using Perl's CGI module, you can capture parameters using the aptly-named param()
method:
#! perluse strict;
use warnings;
use CGI;
use CGI::Carp qw(fatalsToBrowser); # just to make it easier to see errorsmy $cgi = CGI->new;
my $ip_string = $cgi->param('user_ips');
my @ips = split(';', $ip_string);
my $results;
foreachmy $ip (@ips) {
# do whatever here to populate $results
}
# send results back to jQueryprint $cgi->header( -type =>'text/plain', -status =>'200' );
print $results;
print $cgi->end_html;
1;
Make sure you add the appropriate header that corresponds to the statusCode
in the $.ajax()
method and also call end_html()
at the end of the Perl script, otherwise the jQuery/JavaScript may not understand/capture the results.
Post a Comment for "How To Pass A Variable Value From Javascript To Perl"