2013-07-20 45 views
0

我正在嘗試使用jQuery讀取和寫入文本文件。我已經寫了函數來讀取一個文件;但我不能做的是寫入一個文件。我有兩個文件,read.txtwrite.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; 
+3

您需要一個服務器端腳本來處理您的請求並更新文件 – 19greg96

+0

我可以在perl中執行嗎?我應該在哪裏放這個腳本? – Armida

+0

http://perldoc.perl.org/CGI.html(我猜) –

回答

7

您不能使用Javascript/jQuery的文件寫入出於安全原因,因爲,如果我們能,一遊客用他的控制檯可以很容易地改變文件的URL來編輯併產生相應的損害。欲瞭解更多解釋,你可以看看this page

所以,爲了解決你的問題,我認爲最好的辦法是創建一個php文件,它將能夠更新你的服務器文件,併發送到這個PHP文件的文件的內容來更新ajax 。

+0

剛剛編輯我的問題有完整的代碼。有沒有其他的方式,我可以用Perl來做到這一點? – Armida

+0

是的,我認爲,但我不與Perl合作,我不能確切地說如何做。但我認爲你可以看看這個頁面:http://www.gossland.com/perlcourse/files/editing –

+0

另一種方式只是使用jQuery和HTML而不使用get和post?可能嗎?謝謝 – Armida