2013-05-03 100 views
1

我是一個完整的Perl新手& Javascript/jquery/Ajax。例如,我想將字符串var exampleString發送到test.pl,然後腳本將字符串寫入文件。如何在Perl腳本中使用JQuery/Javascript變量的值?

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

你想使用get或post方法發送它嗎? – MikeB 2013-05-03 19:06:39

+0

@MikeB我不得不查看兩者之間的差異,我不得不說不?我只想讓perl腳本抓住字符串變量'exampleString',執行並將字符串保存到服務器上的文本文件中;客戶端不會顯示任何數據。 – Steve 2013-05-03 19:13:14

+0

在這種情況下,您可能想要使用post方法並只抓取消息的整個主體。這就是說,我並沒有試圖變得暴躁,get和post是webapps的基本概念;你可能應該花一點時間瞭解你正在使用的工具。 – 2013-05-03 19:36:14

回答

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; 
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處理程序顯示。

相關問題