我正在嘗試使用jQuery讀取和寫入文本文件。我已經寫了函數來讀取一個文件;但我不能做的是寫入一個文件。我有兩個文件,read.txt
和write.txt
,與代碼位於同一文件夾中。用jQuery寫入文本文件
兩個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;
您需要一個服務器端腳本來處理您的請求並更新文件 – 19greg96
我可以在perl中執行嗎?我應該在哪裏放這個腳本? – Armida
http://perldoc.perl.org/CGI.html(我猜) –