【问题标题】:How can I use the value of a JQuery/Javascript variable in a Perl script?如何在 Perl 脚本中使用 JQuery/Javascript 变量的值?
【发布时间】:2013-04-28 06:19:12
【问题描述】:

我是 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');
            }
}

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;

任何帮助将不胜感激。

【问题讨论】:

  • 你想用get还是post方法发送?
  • @MikeB 我必须查找两者之间的区别,我不得不说两者都没有?我只是想让 perl 脚本抓取字符串变量exampleString,执行并将字符串保存到服务器上的文本文件中;客户端不会显示任何数据。
  • 在这种情况下,您可能想使用 post 方法并获取整个消息正文。也就是说,我并不是要刻薄,get 和 post 是 webapps 的基本概念;您可能应该花一点时间了解您正在使用的工具。

标签: jquery ajax perl cgi


【解决方案1】:

你可能想要类似的东西

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;

【讨论】:

    【解决方案2】:

    这是一个使用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 处理程序显示。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多