我正在尝试使用 jQuery 读取和写入文本文件。我已经编写了读取文件的函数;但我不能做的是写入文件。我有 2 个文件,read.txt
并且write.txt
与代码位于同一文件夹中。
两个 jQuery 函数(如下,以及周围的服务器端 Perl 代码)是:
<!-- language: perl -->
my $script = qq{
\$(document).ready(function() {
\$("#readFile").click(function() {
\$.get('read.txt', function(data) {
\$("#container").val(data);
}, 'text');
});
});
\$.ajax({
url: './test.pl',
data: {
'myString' : "#cont"
},
success: function(data, textStatus, jqXHR) {
alert('string saved to file');
}
});
};
my $q = new CGI;
print $q->header;
print $q->start_html(
-title => "Read a File",
-style => {-src => 'css/ui-lightness/jquery-ui-1.10.3.custom.css" rel="stylesheet'},
-script => [
{-src => 'js/jquery-1.9.1.js'},
{-src => 'js/jquery-ui-1.10.3.custom.js'},
],
);
print $q->start_form;
print $q->textfield(
-style => 'font-family:verdana;width:300px;font-size:13px',
-id => 'container',
-value => '',
);
print $q->button(
-id => 'readFile',
-name => 'submit_form',
-value => 'Read',
);
print $q->textfield(
-style => 'font-family:verdana;width:300px;font-size:13px',
-id => 'cont',
-value => '',
);
print $q->submit(
-id => 'writeFile',
-name => 'submit_form',
-value => 'Write',
);
print $q->script($script);
print $q->end_html;
test.pl
use CGI ();
my $cgi = CGI->new;
print $cgi->header;
my $string = $cgi->param("myString");
open (FILE, ">", "./write.txt") || die "Could not open: $!";
print FILE $string;
close FILE;