在 JavaScript 方面,您需要向 Perl 脚本发送 GET 请求。我只使用 jQuery 完成了此操作(请参阅docs http://api.jquery.com/jquery.ajax/)所以如果你想要一个纯 JavaScript 解决方案,你需要调整它:
function getUserIp(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);
}
}
});
}
请注意,ips
当你将变量传递给 Perl 时,它应该是一个字符串。您可以将参数数组传递给 Perl(请参阅CGI docs https://metacpan.org/pod/CGI#Fetching-the-names-of-all-the-parameters-passed-to-your-script),但我发现事后分割字符串是最可靠的。
我将展示如何使用 Perl CGI 捕获参数,因为它很简单,但如果您打算制作一个完整的网站,那么我强烈建议使用 Web 框架。 Perl 有几个,比如Catalyst http://www.catalystframework.org/ and 莫乔利西斯 https://mojolicious.org/,具有不同的学习曲线。
使用 Perl 的 CGI 模块,您可以使用适当命名的函数捕获参数param()
method:
#! perl
use strict;
use warnings;
use CGI;
use CGI::Carp qw(fatalsToBrowser); # just to make it easier to see errors
my $cgi = CGI->new;
my $ip_string = $cgi->param('user_ips');
my @ips = split(';', $ip_string);
my $results;
foreach my $ip (@ips) {
# do whatever here to populate $results
}
# send results back to jQuery
print $cgi->header( -type => 'text/plain', -status => '200' );
print $results;
print $cgi->end_html;
1;
确保添加对应于的适当标头statusCode
in the $.ajax()
方法并调用end_html()
位于 Perl 脚本的末尾,否则 jQuery/JavaScript 可能无法理解/捕获结果。