1

我是 Perl 和 Javascript/Jquery/Ajax 的新手。例如,我想将字符串 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');
            }
}

测试.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;

任何帮助将非常感激。

4

2 回答 2

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;
于 2013-05-03T19:19:40.610 回答
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 处理程序显示。

于 2013-05-03T19:26:54.870 回答