我是Perl& amp;的全新手。使用Javascript / jQuery的/阿贾克斯。作为一个例子,我想将字符串var exampleString
发送到test.pl,然后脚本将字符串写入文件。
function sendToScript{
var exampleString = 'this is a string';
$.ajax({
url: './test.pl',
data: exampleString,
success: function(data, textStatus, jqXHR) {
alert('string saved to file');
}
}
test.pl
#!/usr/bin/perl -w
use strict;
#How do I grab exampleString and set it to $string?
open (FILE, ">", "./text.txt") || die "Could not open: $!";
print FILE $string;
close FILE;
非常感谢任何帮助。
答案 0 :(得分:2)
你可能想要像
这样的东西var exampleString = 'this is a string';
$.ajax({
url: './test.pl',
data: {
'myString' : exampleString
},
success: function(data, textStatus, jqXHR) {
alert('string saved to file');
}
});
和test.pl
#!/usr/bin/perl -w
use strict;
use CGI ();
my $cgi = CGI->new;
print $cgi->header;
my $string = $cgi->param("myString");
open (FILE, ">", "./text.txt") || die "Could not open: $!";
print FILE $string;
close FILE;
答案 1 :(得分:0)
以下是使用Mojolicious框架的示例。它可以在CGI,mod_perl,PSGI或其自己的内置服务器下运行。
#!/usr/bin/env perl
use Mojolicious::Lite;
any '/' => 'index';
any '/save' => sub {
my $self = shift;
my $output = 'text.txt';
open my $fh, '>>', $output or die "Cannot open $output";
print $fh $self->req->body . "\n";
$self->render( text => 'Stored by Perl' );
};
app->start;
__DATA__
@@ index.html.ep
<!DOCTYPE html>
<html>
<head>
%= t title => 'Sending to Perl'
</head>
<body>
<p>Sending</p>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
%= javascript begin
function sendToScript (string) {
$.post('/save', string, function (data) { alert(data) });
}
$(function(){sendToScript('this is a string')});
% end
</body>
</html>
将其保存到文件(例如test.pl
)和将启动内部服务器的运行./test.pl daemon
。
基本上它设置了两条路由,/
路由是面向用户的页面,它运行javascript请求。 /save
路由是javascript将数据发布到的路由。控制器回调将完整的帖子主体附加到文件,然后发回确认消息,然后由成功的javascript处理程序显示。