How can I use the value of a JQuery/Javascript var

2019-08-11 06:03发布

I am a complete newbie to Perl & Javascript/Jquery/Ajax. As an example, I'd like to send the string var exampleString to test.pl, and the script will then write the string to file.

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;

Any help would be much appreciated.

2条回答
再贱就再见
2楼-- · 2019-08-11 06:17

You probably want something like

var exampleString = 'this is a string';
$.ajax({
    url: './test.pl',
    data: {
        'myString' : exampleString
    },
    success: function(data, textStatus, jqXHR) {
        alert('string saved to file');
    }
});

and 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;
查看更多
Explosion°爆炸
3楼-- · 2019-08-11 06:24

Here is an example using the Mojolicious framework. It can be run under CGI, mod_perl, PSGI or its own built-in servers.

#!/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>

save that to a file (say test.pl) and the run ./test.pl daemon which will start the internal server.

Basically it sets up two routes, the / route is the user-facing page which runs the javascript request. The /save route is the one that the javascript posts the data to. The controller callback appends the full post body to the file and then sends a confirmation message back which is then displayed by the success javascript handler.

查看更多
登录 后发表回答